var totalSize = 10 * 1024 * 1024;
// var currentSize = 10 * 1024 * 1024;
// var attachmentNumber = 0;
// var entries = new Array();

// python版本写信系统
var WriteMail = Class.create();
WriteMail.prototype = {
 	initialize : function() {
		this._initConst();
        this.is_tourial = false;
	},
	
	addMethod: function(name, func, rewrite) {
		if(typeof func != 'function') return;
		if(this[name] && rewrite === false) return;
		this[name] = func;
	},
	
	// 初始化事件代理
	initEvent: function() {
		var self = this;
		// 写信页面的click事件代理
		var _tmp_dl = [
			{name: 's_single_send', exec: function(EL, event) {
				self.isSingleSend(EL, event);
			}},
			{name: 's_letter', exec: function(EL, event) {
				self.setLetter(EL, event);
			}},
			{name: 's_postcard', exec: function(EL, event) {
				self.setPostcard(EL, event);
			}},
			{name: 's_show_postcard', exec: function(EL, event) {
				changePanel('composeMail');
			}},
			{name: 's_show_convey', exec: function(EL, event) {
				changePanel('composeMail');
			}},
			{name: 's_convey', exec: function(EL, event) {
				self.setConvey(EL, event);
			}},
			{name: 's_editor_change', exec: function(EL, event) {
				self.clickEditorChange();
			}},
			{name: 's_unuse_postcard', exec: function(EL, event) {
				changePanel('composeMail');
			}},
			
			{name: 's_unuse_convey', exec: function(EL, event) {
				changePanel('composeMail');
			}},
			{name: 's_use_postcard', exec: function(EL, event) {
				changePanel('composeCardMail', null, null, true);
			}},
			// 文本编辑状态下点击进入传情贺卡功能页面
			{name: 's_use_convey', exec: function(EL, event) {
				changePanel('userMail', null, null, true);
			}},
			// 取消传情计划的定制
			{name: 's_cancel_convey', exec: function(EL, event) {
				hiddenAllPanel();
				DOM.mailConfiguration.show();
            	custom_mail_display.initPageWithData(custom_mail_display.customMailCache.data);
			}},
			// 如果没有联系人，在写信页面的右侧可以直接添加联系人
			{name: 's_no_addr_add', exec: function(EL, event) {
				self.saveAddr(EL, event, true);
			}},
			// 写信页面右侧地址簿事件
			{name: 's_address_input', exec: function(EL, event) {
				var _name = EL.cname ? EL.cname : EL.getAttribute('cname'),
				_email = EL.cemail ? EL.cemail : EL.getAttribute('cemail');
				copyAddressBook(_name, _email);
			}},
			{name: 's_group_input', exec: function(EL, event) {
				var _name = EL.gname ? EL.gname : EL.getAttribute('gname');
				inputGroupMail(_name);
			}},
			{name: 's_address_more', exec: function(EL, event) {
				isShowAllRecent(EL);
			}},
			{name: 's_show_group', exec: function(EL, event) {
				var _id = EL.gid ? EL.gid : EL.getAttribute('gid');
				isShowAddrGroup(EL, _id);
			}},
			{name: 's_check_save', exec: function(EL, event) {
				clicksave(EL.checked);
			}},
			{name: 's_show_mailcc', exec: function(EL, event) {
				self.cc_toggle('mail.cc', 'compose.wcc');
			}},
			{name: 's_show_mailbcc', exec: function(EL, event) {
				self.cc_toggle('mail.bcc', 'compose.wbcc');
			}},
			{name: 'disposition_checkbox', exec: function(EL, event) {
            	self.disposition_notifier_click();
			}},
			{name: 's_send_mail', exec: function(EL, event) {
				clickSubmit();
			}},
			{name: 's_save_mail', exec: function(EL, event) {
				clickStore('userclick');
			}},
			{name: 's_send_postcard', exec: function(EL, event) {
				clickCardSubmit();
			}},
			{name: 's_send_convey', exec: function(EL, event) {
				custom_mail_display.submitMail();
			}}
		];
		
		var _tmp_dl_md = [
			{name: 's_send_mail', exec: function(EL, event) {
				clickSubmit();
			}},
			{name: 's_save_mail', exec: function(EL, event) {
				clickStore('userclick');
			}},
			{name: 's_send_postcard', exec: function(EL, event) {
				clickCardSubmit();
			}},
			{name: 's_send_convey', exec: function(EL, event) {
				custom_mail_display.submitMail();
			}}
		];
		
		// 写信页面的mouseover的事件代理
		var _tmp_over_dl = [
			{name: 's_letter', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_letter') ? EL : Element.hasClassName(EL.parentNode, 's_letter') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.addClassName(e, 'letter-over');
			}},
			{name: 's_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_postcard') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.addClassName(e, 'letter-over');
			}},
			{name: 's_unuse_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_unuse_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_unuse_postcard') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.addClassName(e, 'letter-over');
			}},
			{name: 's_convey', exec: function(EL, event) {
				var e = EL.hasClassName('s_convey') ? EL : EL.parentNode.hasClassName('s_convey') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.addClassName(e, 'letter-over');
			}},
			{name: 's_unuse_convey', exec: function(EL, event) {
				var e = EL.hasClassName('s_unuse_convey') ? EL : EL.parentNode.hasClassName('s_unuse_convey') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.addClassName(e, 'letter-over');
			}},
			{name: 's_editor_change', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_editor_change') ? EL : Element.hasClassName(EL.parentNode, 's_editor_change') ? EL.parentNode : Element.hasClassName(EL.parentNode.parentNode, 's_editor_change') ? EL.parentNode.parentNode : null;
				Element.addClassName(e, 'item-focus');
			}},
			{name: 's_use_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_use_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_use_postcard') ? EL.parentNode : Element.hasClassName(EL.parentNode.parentNode, 's_use_postcard') ? EL.parentNode.parentNode : null;
				Element.addClassName(e, 'item-focus');
			}},
			{name: 's_single_send', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_single_send') ? EL : Element.hasClassName(EL.parentNode, 's_single_send') ? EL.parentNode : Element.hasClassName(EL.parentNode.parentNode, 's_single_send') ? EL.parentNode.parentNode : null;
				self.showSingleSend(e);
			}},
			{name: 's_use_convey', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_use_convey') ? EL : Element.hasClassName(EL.parentNode, 's_use_convey') ? EL.parentNode : null;
				Element.addClassName(e, 'item-focus');
			}},
			{name: 's_group_input', exec: function(EL, event) {
				EL.style.textDecoration = 'underline';
			}}
		];
		
		// 写信页面的mouseout事件
		var _tmp_out_dl = [
			{name: 's_letter', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_letter') ? EL : Element.hasClassName(EL.parentNode, 's_letter') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.removeClassName(e, 'letter-over');
			}},
			{name: 's_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_postcard') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.removeClassName(e, 'letter-over');
			}},
			{name: 's_unuse_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_unuse_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_unuse_postcard') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.removeClassName(e, 'letter-over');
			}},
			{name: 's_convey', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_convey') ? EL : Element.hasClassName(EL.parentNode, 's_convey') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.removeClassName(e, 'letter-over');
			}},
			{name: 's_unuse_convey', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_unuse_convey') ? EL : Element.hasClassName(EL.parentNode, 's_unuse_convey') ? EL.parentNode : null;
				if(self.focusLetterEL && self.focusLetterEL == e) return false;
				Element.removeClassName(e, 'letter-over');
			}},
			{name: 's_editor_change', exec: function(EL, event) {
				var e = EL.hasClassName('s_editor_change') ? EL : EL.parentNode.hasClassName('s_editor_change') ? EL.parentNode : null;
				Element.removeClassName(e, 'item-focus');
			}},
			{name: 's_use_postcard', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_use_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_use_postcard') ? EL.parentNode : null;
				Element.removeClassName(e, 'item-focus');
			}},
			{name: 's_single_send', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_single_send') ? EL : Element.hasClassName(EL.parentNode, 's_single_send') ? EL.parentNode : Element.hasClassName(EL.parentNode.parentNode, 's_single_send') ? EL.parentNode.parentNode : null;
				if(self._single_float_over) return false;
				self.hideSingleSend(e);
			}},
			{name: 's_use_convey', exec: function(EL, event) {
				var e = Element.hasClassName(EL, 's_use_convey') ? EL : Element.hasClassName(EL.parentNode, 's_use_convey') ? EL.parentNode : null;
				Element.removeClassName(e, 'item-focus');
			}},
			{name: 's_group_input', exec: function(EL, event) {
				EL.style.textDecoration = 'none';
			}}
		];
		
		var _gpcn = Element.getParentNodeByClassName, _gpatr = Element.getParentNodeByAttribute;
		DOM.composeMail.observe('click', function(event) {
			var el = event.target;
			_tmp_dl.each(function(item) {
				try {
					var e = _gpcn(el, item.name);
					if(e) {
						item.exec(e, event);
						if(e && e.nodeName.toLowerCase() == 'a') Event.stop(event);
					}
				} catch(e) {}
				return false;
			});
			if(el.nodeName.toLowerCase() == 'a') {
				Event.stop(event);
			}
		}).observe('mouseover', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-hover');
			(function() {
				_tmp_over_dl.each(function(item) {
					try {
						var e = _gpcn(el, item.name);
						if (e) {
							item.exec(e, event);
						}
						Event.stop(event);
					} catch(e) {}
					return false;
				});
			})();
		}).observe('mouseout', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-hover');
			(function() {
				_tmp_out_dl.each(function(item) {
					try {
						var e = _gpcn(el, item.name);
						if (e) {
							item.exec(e, event);
						}
						Event.stop(event);
					} catch(e) {}
					return false;
				});
			})();
		}).observe('mousedown', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).addClassName('bt-common-press');
		}.bind(this)).observe('mouseup', function(event) {
			var el = event.target, e = _gpcn(el, 'bt-common');
			e && $(e).removeClassName('bt-common-press');
		});
		
		
		var _tmp_sc_dl = [
			{name: 's_succ_save', exec: function(EL, event) {
				self.saveAddr(EL, event);
			}},
			{name: 's_set_send_save', exec: function(EL, event) {
				self.autoSaveSendMailList(EL, self.tmpMailList, true);
			}},
			{name: 's_succ_group', exec: function(EL, event) {
				self.showgroupel(EL, 'groupel');
			}},
			{name: 's_succ_maillist', exec: function() {
				changePanel('mailList', 1);
			}},
			{name: 's_succ_write', exec: function() {
				changePanel('composeMail');
			}}
		];
		
		DOM.sendSuc.observe('click', function(event) {
			var el = event.target;
			_tmp_sc_dl.each(function(item){
				var e = _gpcn(el, item.name);
				if(e) {
					item.exec(e, event);
				}
				if(e && e.nodeName.toLowerCase() == 'a') {
					Event.stop(event);
				}
				return false;
			});
		});
	},
    //分送的弹出提示
    s_send_prompt: function(show, p_left, p_top){
		p_left -= 24;
        var self = this;
        //如果show为true,那么就显示,否则就删除
        var xe = $('s_send');
        if (!xe) {
            try {
                var _div = document.createElement('div');
                _div.id = "s_send";
                with (_div.style) {
                    if (Prototype.Browser.IE) {
                        filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + MailConst.IMG + '/../all/tip_up.png\')';
                    } else {
                        background = 'url(' + MailConst.IMG + '/../all/tip_up.png) no-repeat';
                    }
                    position = 'absolute';
                    zIndex = '888';
                    left = p_left + 'px';
                    top = (p_top + 15) + 'px';
                    width = '110px';
                    height = '80px';
					cursor = 'pointer';
                };
                _div.innerHTML = '<div style="margin:25px 10px 10px 10px;"> 了解什么是邮件分送>> </div>';
                DOM.sohuMailMain.appendChild(_div);
				Event.observe(_div, 'click', function(event) {
					window.open('http://mail.sohu.com/mapp/help/mail/help11.jsp');
					return false;
				});
                Event.observe(_div, 'mouseover', function(event){
                    self._single_float_over = true;
                });
                Event.observe(_div, 'mouseout', function(event){
                    self._single_float_over = false;
                    
                });
                xe = _div;
            } catch (e) {}
        }
        try {
            if (show) {
                xe.setStyle({'left': p_left + 'px'});
                xe.show();
            } else {
				if(this._single_float_over) {
					var _sf = arguments.callee;
					var __t = setTimeout(function() {
						_sf.apply(self, [show, p_left, p_top]);
					}, 500);
					return false;
				}
                xe.hide();
            }
        } catch (e) { }        
    },
	// 显示单封发送的提示层
    showSingleSend: function(e){
		return;
		var self = this;
        try {
            //弹出地址簿的弹出层
            this._single_send_time_out = setTimeout(function(){
                clearTimeout(self._single_send_time_out);
                self._single_send_time_out = null;
                var p = Element.cumulativeOffset(e);
                if (p.left > 30) {
                    self.s_send_prompt(true, p.left, p.top);
                }
            }, 500);
        } catch (e) {}
    },
	// 隐藏单封发送的提示层
    hideSingleSend: function(e){
        try {
			var self = this;
            //弹出地址簿的弹出层
            var s = $('s_send');
            if (!s || !s.visible()) {
                try {
                    clearTimeout(this._single_send_time_out);
                    this._single_send_time_out = null;
                    var p = Element.cumulativeOffset(e);
                    this.s_send_prompt(false, p.left, p.top);
                } catch (e) { }
            } else {
                var _lazy_disappear = setTimeout(function(){
                    clearTimeout(_lazy_disappear);
                    _lazy_disappear = null;
                    clearTimeout(self._single_send_time_out);
                    self._single_send_time_out = null;
                    var p = Element.cumulativeOffset(e);
                    self.s_send_prompt(false, p.left, p.top);
                }, 500);
                return;
            }
        } catch (e) { }
    },
	
	// 信纸、明信片的选择区域效果
	listenEvent: function(id, callback) {
		var pel = $(id), self = this;
		$A(pel.childNodes).each(function(item) {
			Event.observe(item, 'mouseover', function(event) {
				if(self.focusLetterEL && self.focusLetterEL == this) return false;
				try {
					Element.addClassName(this, 'letter-over');
				} catch(e) {}
			});
			Event.observe(item, 'mouseout', function(event) {
				if(self.focusLetterEL && self.focusLetterEL == this) return false;
				try {
					Element.removeClassName(this, 'letter-over');
				} catch(e) {}
			});
			Event.observe(item, 'click', function(event) {
				if(self.focusLetterEL && self.focusLetterEL == this) return false;
				try {
					if(self.focusLetterEL && self.focusLetterEL == this) return false;
					try {
						self.focusLetterEL && Element.removeClassName(self.focusLetterEL, 'letter-focus');
					} catch(e) {}
					try {
						Element.removeClassName(this, 'letter-over');
					} catch(e) {}
					try {
						Element.addClassName(this, 'letter-focus');
					} catch(e) {}
					try {
						self.focusLetterEL = this;
					} catch(e) {}
					try {
						if(callback) callback(event, this);
					} catch(e) {}
				} catch(e) {}
			});
		});
	},
	
	// 初始化自动匹配事件的绑定
	initAutocomplete: function() {
		try {
			!this.autocomplete && (function() {
				this.autocomplete = {};
				this.autocomplete['to']  = new AddressFilter('compose.wto', DOM.composeMail, reAutoLists());
				this.autocomplete['cc']  = new AddressFilter('compose.wcc', DOM.composeMail, reAutoLists());
				this.autocomplete['bcc'] = new AddressFilter('compose.wbcc', DOM.composeMail, reAutoLists());
				Event.observe('compose.mess1', 'focus', function(event) {
					Editor.focus();
				});
			}.bind(this))();
		} catch(e) {}
	},

	writeNewMail : function() {
		ExecFunc("filterBeforeWriteMail",true);
		if(!listenVolume()) return false;
        try{
            if(parseInt(arguments[1]) == 1){
                this.is_tourial = true;
            }
        }catch(e){ }
        //单封发送标记取消
        try{
			this.isSetSingleSend(false);
        }catch(e){}
		this.thisIsDraftToWriteMail = false;
        this.defaulteditor = mailCfgClass.getProfileContent().defaulteditor ? mailCfgClass.getProfileContent().defaulteditor : 'html';
		try {
			changeToolbarStyle('');
		} catch (e) {}
		// hideEditorDiv();
		// DOM.mail_operate_message.innerHTML = "";
		DOM.upload_iframe_content.innerHTML = "";
		mailUploadFile.init();
		// 为上传附件创建form表单
		mailUploadFile.createForm();
		DOM.compose_subject.value = this.subject;
		DOM.compose_wto.value = this.to;
		DOM.compose_wcc.value = this.cc;
		DOM.compose_wbcc.value = this.bcc;
		!this.cc.blank() ? DOM.mail_cc.show() : DOM.mail_cc.hide();
		!this.bcc.blank() ? DOM.mail_bcc.show() : DOM.mail_bcc.hide();
		DOM.securityCode.value = "";
		// DOM.checkSign.checked = false;
		uploadFileNameArray = [];
		DOM.uploadInfoDIV.innerHTML = '';
		DOM.uploadInfoDIV.hide();
		appendAddressBook();
		// 改变界面UI元素
		resizeWriteAreaHeight();
		try {
			Element.show(DOM.compose_wto.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling.nextSibling);
		} catch(e) {}
		if (this.defaulteditor == "text") {
			// DOM.compose_editer.innerHTML = '切换为HTML';
			DOM.compose_mess1.hide();
			DOM.compose_mess2.show();
			// DOM.user_sign_area.hide();
		} else {
			// DOM.compose_editer.innerHTML = '切换为纯文本';
			DOM.compose_mess1.show();
			DOM.compose_mess2.hide();
			// DOM.user_sign_area.show();
		}
		var self = this;
		var _r = arguments[0];
		hiddenAllPanel();
		try {
			if(!DOM.write_letter_operate) DOM.write_letter_operate = $('write_letter_operate');
			DOM.write_letter_operate.hide();
			var _ult = $('use_letter');
			_ult.removeClassName('item-focus');
			_ult.removeAttribute('isfocus');
		} catch(e) {}
		try {
			if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
			if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
			DOM.top_operate_area.innerHTML = common_top_html;
			DOM.bottom_operate_area.innerHTML = common_bottom_html;
		} catch(e) {}
		try {
			// this._clickSave(this.is_save ? true : false);
		} catch(e) {}
		try {
			this.writeFunc.each(function(item, index) {
				var _item = $(item);
				if(index == 0) {
					try {
						_item.show();
						_item.style.visibility = 'visible';
					} catch(e) {}
				} else {
					try {
						_item.hide();
						_item.style.visibility = 'hidden';
					} catch(e) {}
				}
			});
		} catch(e) {}
		try {
			if(this.focusLetterEL) {
				Element.removeClassName(this.focusLetterEL, 'letter-focus');
				this.focusLetterEL = null;
			}
		} catch(e) {}
		DOM.composeMail.show();
        //能否使用U盘
		try {
			$('ID_WRITEMAIL_CALLUDISK').setStyle({
				'display': G.hasUDiskRights() ? '' : 'none'
			});
		} catch(e) {}
		// 初始化写信页面的autocomplete事件
		try {
			this.initAutocomplete();
		} catch(e) {}
        try{
			/*
        	if( DOM.composeMail.lastChild.id != "panel_div" ){
            	Element.insert( DOM.composeMail, { bottom : panel_str } );
            }
            */
        } catch( e ){}
		var self = this;
		var ts = setTimeout(function() {
			clearTimeout(ts);
			ts = null;
			try {
				self.setContentInput(self.content);
			} catch(e) {}
			try {
				// 如果用户设置了签名，并且是打开的状态，自动将签名插入编辑器中
				self.addSign();
			} catch(e) {}
			try {
				self.content = self.getContentInput();
			} catch(e) {}
		}, 100);
		
		this.AutoStore.restart();
		try {
			deleteLoadPage();
		} catch(e) {}
		// SOT Start 绑定单选框和下拉框区域
		var t2 = setTimeout(function() {
			clearTimeout(t2);
			t2 = null;
			try {
				sendontime.setCheckBox('sot_control', 'sohu_sot_container');
				sendontime.initUIString();
			} catch(e) {}
		}, 10);
		// SOT End
		try {
			RUpload.init();
		} catch(e) {}
        //add by zhangyinghui 
        var urlParams = G.ANCHOR_PARAMETERS;
        G.ANCHOR_PARAMETERS={};

		
		try{			
            if(urlParams["to"]){
                $('compose.wto').value=urlParams["to"];
            }
		} catch(e) { }
        //U盘接口
		try{
            var content_from_udisk = "";
            if(urlParams["addtype"] && urlParams["addtype"][0] == "attachement" && urlParams["info"]){
                var infos = urlParams["info"];
                var n = infos.length;
                for (var i=0;i<n ;i++ ){
                   var fileinfo = infos[i].split("|");
                   var fileid = fileinfo[ 0 ];
                   var filename = decodeURI( fileinfo[ 1 ] );
                   var fileexpire = fileinfo[ 2 ];
                   if( fileexpire + "" == "20200101" ){
                     fileexpire = "同手机邮件到期时间";
                   }
                   else{
                    fileexpire = fileexpire.substr( 0, 4 ) + "-" + fileexpire.substr( 4, 2 ) + "-" + fileexpire.substr( 6, 2 );
                   }
                   content_from_udisk += "<br />" + filename + "  ";
                   content_from_udisk += "<a target='_blank' href='http://u.sohu.com/downloadFile.action?fileid=" + fileid + "'>"
                               + "http://u.sohu.com/downloadFile.action?fileid=" + fileid 
                               + "</a>   "
                               + "文件有效期至：" + fileexpire;
                }//end for
            }//end if
            
            if(content_from_udisk){
                content_from_udisk = "<div id='UDiskPanel'><br /><br />"
                        + "-----"
                        + "（下面的连接是您的朋友通过"+ USE_SYS.title +"网络U盘给您的共享附件，您可下载）"
                        + content_from_udisk
                        + "</div>";

            }
            var uTimer = setTimeout(function(){
                    clearTimeout(uTimer);
                    content_from_udisk = content_from_udisk+self.getContentInput();
                    self.setContentInput(content_from_udisk);
            }, 1000);
            
        } catch(e){ }
		try {
			(function(){
				var _mf = $('mail.from');
				var _fl = [{
					text: UserSohuID,
					exec: function(event) {
						_mf.setAttribute('xfrom', UserSohuID);
					}
				}], _fhtml = [];
				for (var i in mailPop.PopAccounts) {
					// _fl.push(mailPop.PopAccounts[i]['folder']['name']);
					(function() {
						var _n = mailPop.PopAccounts[i]['folder']['name'];
						_fl.push({
							text: _n,
							exec: function(event) {
								_mf.setAttribute('xfrom', _n);
							}
						});
					})();
				}
				if (_fl.length > 1) {
					var _select = document.createElement('select');
					_fl.each(function(item){
						_fhtml.push('<option value="' + item + '">' + item + '</option>');
					});
					// _mf.innerHTML = '<li>发件人：<select>' + _fhtml.join('') + '</select></li>';
					_mf.innerHTML = '<li><span style="float:left;margin-left:0;">发件人：</span><span style="float:left;margin-left:0;"></span></li>';
					_mf.show();
					new Select().init(_mf.getElementsByTagName('span')[1], _fl);
				} else {
					_mf.hide();
				}
			})();
		} catch(e) {}
       	// alva disposition mail
		try {
			$('disposition_notifier').checked = false;
		} catch(e) {}
        write_mail_dispostion_flag = 0;
		DOM.compose_wto.focus();
		try {
			deleteLoadPage();
		} catch(e) {}
		addAjaxHistory("writeMail", "changePanel('composeMail', null, true);", "写邮件", _r);
	},
	
	// 是否显示明信片
	showLetter: function() {
		try {
			if (!DOM.write_letter_operate) DOM.write_letter_operate = $('write_letter_operate');	
		} catch(e) {}
		var slide_flag = false;
		try {
			DOM.write_letter_operate.visible() ? 
				(function() {
					// DOM.write_letter_operate.hide();
					slide_flag = false;
				})() : (function() {
					DOM.write_letter_operate.show();
					slide_flag = true;
				})();
		} catch(e) {}
		try {
			if(!this.scrollAnimation) {
				var sta_name = ['no','classical','meihua','xieyi','xinzhi_04','xinzhi_05','xinzhi_06','xinzhi_07','xinzhi_08','xinzhi_09','xinzhi_10','xinzhi_11'];
				DOM.write_letter_operate.innerHTML = stationeryBookHTML(sta_name);
				this.scrollAnimation = new ScrollAnimation('letter_scroll_area');
				this.scrollAnimation.mouseWheel();
				var self = this;
				Event.observe('letter_scroll_right', 'click', function(event) {
					self.scrollAnimation.scrollRight();
				});
				Event.observe('letter_scroll_left', 'click', function(event) {
					self.scrollAnimation.scrollLeft();
				});
			}
		} catch(e) {}
		var _ul = $('use_letter');
		try {
			if(slide_flag == true) {
				this.scrollAnimation.slideDown(DOM.write_letter_operate, 70);
				if(_ul) {
					try {
						_ul.addClassName('item-focus');
					} catch(e) {}
					try {
						_ul.setAttribute('isfocus', 'true');
					} catch(e) {}
				}
			} else {
				this.scrollAnimation.slideUp(DOM.write_letter_operate, 70);
				if(_ul) {
					try {
						_ul.removeClassName('item-focus');
					} catch(e) {}
					try {
						_ul.removeAttribute('isfocus', 'true');
					} catch(e) {}
				}
			}
		} catch(e) {}
	},

	_initConst : function() {
		this.defaulteditor = mailCfgClass.getProfileContent().defaulteditor ? mailCfgClass.getProfileContent().defaulteditor : 'html';
		// this.autosave = false;
		this.is_save = mailCfgClass.getProfileContent().autosave == false ? 0 : 1;
		this.legitimate = true;
		// 信件参数
		this.stationery = "";
		this.is_html;
		this.subject = "";
		this.to = "";
		this.cc = "";
		this.bcc = "";
		var _ct = this.getContentInput();
		this.content = _ct && typeof _ct == 'string' ? _ct : '';
		this.securityCode="";
		this.text = "";
		
		this.origin;
		this.attachment;
		this.attDivContent = "";
		// 信纸
		this.draftParams;
		this.autoStored = false;
		// 保存草稿的ID值
		this.draftAutoSaveId = 0;
		this.sendSucMailList = new Array();
		this.mailMiscHeaders = new Array();
		// 记录一下如果是从草稿箱进入写信状态的，为了在写完信发出成功之后将草稿删除
		this.thisIsDraftToWriteMail = false;
		this.draftContent = "";
		// 信件正在发送过程中....
		this.thisCurrentMailisSending = false;
		// 附件上传完毕之后是否超出大小
		this.isAfterFileUpload = false;
		// 从上传附件的接口函数中返回的上传附件的总大小
		this.allAttFileSize = 0;
		// 从草稿箱进入到写信状态，记录保存的附件个数，作为在这个基础上添加删除附件的偏移量
		this.savedMailAttachNum = 0;
		// 从读信页面到转发状态，记录附件的情况
		this.forwardMailAttachNum = 0;
		// 用户手动保存草稿（带附件的情况）
		this.userIsSaveDraft = false;
		// 信件发送是否成功
		this.mailIsSuccess = false;
		// 用户是否手动保存草稿
		this.mailIsSave = false;
		
		// 判断是否不写主题发信的flag
		this.send_subj_flag = false;
		// 判断是否填写了“附件”内容，而没有上传附件的flag
		this.send_attc_flag = false;
		// mailUploadFile.init();
		// mailUploadFile.createIframe();
		// 会话对应的唯一值
		this.thread = 0;
		
		// 转发、回复的id,类型
		this.original_id = 0;
		this.draft_type = 0;
		this.message_id = '';
		this.references = [];
		this.reply_to = [];
		this.in_reply_to = [];
		this.mail_followup_to = [];
		// this.deleteSaveId = 0;
		// 发信后记录用户是否使用了地址簿
		this.addressbook_use_flag = 0;
		// 下拉列表的统计
		this.addressbook_use_list = 0;
		try {
			RUpload.init();
		} catch(e) {}
		
		// 信纸中被选中的信纸元素
		this.focusLetterEL = null;
		// 写信页面的功能
		this.writeFunc = ['write_common_mail', 'write_card_mail', 'write_convey_mail'];
		// 鼠标是否在 分发 层之上的浮动
		this._single_float_over = false;
		// 是否使用分发的timer
		this._single_send_time_out = null;
		// 转发的时候原发件人的地址
		this.orig_uid = '';
	},

	checkSendMail : function() {
		if (!this.getSendEmail2ArrayList(DOM.compose_wto.value, true)) {
			DOM.compose_wto.focus();
			return false;
		}
		if (!this.getSendEmail2ArrayList(DOM.compose_wcc.value)) {
			DOM.compose_wcc.focus();
			return false;
		}
		if (!this.getSendEmail2ArrayList(DOM.compose_wbcc.value)) {
			DOM.compose_wbcc.focus();
			return false;
		}
		
		if (DOM.compose_subject.value.blank() && mailUploadFile.FILES_INFOS.length == 0 && !this.send_subj_flag) {
			_dialog.confirm({info: '您确定不写主题就发送吗？', click: function() {
				writemail.send_subj_flag = true;
				var t = setTimeout(function() {
					clearTimeout(t);
					t = null;
					clickSubmit();
				}, 10);
			},
			cancelclick: function() {
				writemail.send_subj_flag = false;
			}});
			DOM.compose_subject.focus();
			return false;
		}
		// 判断邮件内容中如果有“附件”两个字，提示用户是否上传附件
		if(this.getContentInput().include('附件') && !this.send_attc_flag && mailUploadFile.FILES_INFOS.length == 0 && !Editor.c().document.getElementById("UDiskPanel")) {
			_dialog.confirm({info: '您是否忘了粘贴附件？！ 确定要发送目前这封邮件吗？', cancel: '暂不发送', click: function() {
				writemail.send_attc_flag = true;
				var t1 = setTimeout(function() {
					clearTimeout(t1);
					t1 = null;
					clickSubmit();
				}, 10);
			},
			cancelclick: function() {
				writemail.send_attc_flag = false;
				try {
					var _ufa = DOM.upload_file_area.style;
					_ufa.backgroundColor = '#F6AB00';
					_ufa.MozBorderRadius = '3px';
					_ufa.WebkitBorderRadius = '3px';
					_ufa.borderRadius = '3px';
					var _timer = setTimeout(function() {
						_ufa.backgroundColor = '';
						clearTimeout(_timer);
						_timer = null;
					}, 2000);
				} catch(e) {}
			}});
			return false;
		}
		
		if (!this.checkFileUploading()) {
			DOM.compose_subject.focus();
			return false;
		}
		
		//SOT Add 在用户点击提交按钮之后，对用户选择的时间进行简单的判断。
		if ( sendontime.isChecked() && sendontime.checkValid() == false ) {
			_dialog.alert({info: '请设置晚于当前的时间进行定时发送！'});
			return false;
		}
		//SOT Add End
		return true;
	},

	checkFileUploading : function() {
		if (mailUploadFile.uploading) {
			_dialog.alert({info: '附件正在上传中，请稍候！'});
			return false;
		}
		return true;
	},

	clickSendMail : function() {
		if (this.thisCurrentMailisSending) {
			return;
		}
		this.sendSucMailList = [];
		this.is_html = (this.defaulteditor == "text") ? 0 : 1;
		this.subject = DOM.compose_subject.value.escapeHTML();
		this.to = DOM.compose_wto.value;
		this.cc = DOM.compose_wcc.value;
		this.bcc = DOM.compose_wbcc.value;
		// this.securityCode = DOM.securityCode.value;
		this.content = this.getContentInput();
		// this.is_save = true;
		this.origin = 0;
		var ufile = [];
		try {
			mailUploadFile.FILES_INFOS.each(function(item){
				if (item.success) {
					ufile.push(item.id);
				}
			});
		} catch(e) {}
		
		this.attachments = $A(ufile).toJSON();
		var toTmpList = this.getSendEmail2ArrayList(this.to);
		var ccTmpList = this.getSendEmail2ArrayList(this.cc);
		var bccTmpList = this.getSendEmail2ArrayList(this.bcc);
		
		
		//过滤器，在发信前对收件人名单进行检查 主要针对vip
		
		if(ExecFunc("filterBeforeSendMail",{to:toTmpList,cc:ccTmpList,bcc:bccTmpList})===false){
			return;
		}
		
		
		
		this.sendSucMailList = this.sendSucMailList.concat(toTmpList).concat(ccTmpList).concat(bccTmpList);
		
		var html_content = '', text_content = '';
		if(this.defaulteditor == 'html') {
			html_content = this.getContentInput();
			text_content = html_content.stripTags();
		} else {
			text_content = this.getContentInput();
			html_content = text_content.replace(/\n/ig, '<br />');
		}
		var _thread = this.thread;
        var _disposition_notifier = (function() {
			try {
				return $('disposition_notifier').checked;
			} catch(e) {
				return false;
			}
		})();
		
		// 生成key
		mail_send_e.init(['compose.wto'], 6, UID + genKeyCode());
		mail_send_e.genuuid();
		var _env = {
			attach: ufile,
            disposition_notifier: _disposition_notifier == false ? 0 : 1,
			// reply_id: 0,
			// forward_id: 0,
			original_id: this.original_id,
			draft_type: this.draft_type,
			message_id: this.message_id,
			references: this.references,
			reply_to: this.reply_to,
			in_reply_to: this.in_reply_to,
			mail_followup_to: this.mail_followup_to,
			// save_after_send: mailCfgClass.get_profile_content.autosave == false ? 0 : 1,
			// 目前所有发出的邮件都保存的已发送中
			save_after_send: 1,
			save_to_addressbook: mailCfgClass.get_profile_content.autosavesendmail == false ? 0 : 1,
			thread: _thread
		};
		if(this.orig_uid != '') _env.orig_uid = this.orig_uid;
		var snick = (function() {
			try {
				var _fn = mailCfgClass.get_profile_content.fullname;
				return _fn && _fn != '' ? _fn : '';
			} catch(e) {
				return '';
			}
		})();
		var params = {
			id: this.draftAutoSaveId,
			stationery : this.stationery,
			is_send: 1,
			is_html: this.is_html,
			subject: this.subject,
			from: UserSohuID,
			fullname: snick,
			to: toTmpList.join(', '),
			cc: ccTmpList.join(', '),
			bcc: bccTmpList.join(', '),
			html: html_content,
			text: text_content,
			addressbook_use_flag: this.addressbook_use_flag,
			addressbook_use_list: this.addressbook_use_list,
			env: Object.toJSON(_env),
			securityCode: mail_send_e.UUID,
            //单封发送
            single: write_mail_single_flag,
            sendtime: mail_send_e._sendtime
		};
		var _mf = $('mail.from');
		try {
			var _ms = _mf.getAttribute('xfrom');
			if(_ms && _ms != UserSohuID) params.xfrom = _ms;
			/*
			var _ms = _mf.getElementsByTagName('select')[0];
			if(_ms && _ms.options.length > 1) {
				var _xfrom = _ms.options[_ms.selectedIndex].value;
				if(_xfrom != UserSohuID) params.xfrom = _xfrom;
			}
			*/
		} catch(e) {}
		if (this.legitimate) {
			// 发送邮件的遮罩层
			// Tips.show("邮件正在发送，请稍候...");
			Tips.text = '正在发送...';
			this.AutoStore.stop();
			this.thisCurrentMailisSending = true;
			//SOT Add 当定时发送的单选框被选中时，则向SOT的后台发送必须的数据
			if (sendontime.isChecked()) {
				params['sot_time'] = sendontime.getSelectValue();
				params['sot_file'] = sendontime.getFilePath();
				params['sot_mod'] = sendontime.getMod();
				params['sot_id'] = sendontime.getDBID();
				params['sot_senderid'] = PassportSC.cookieHandle('userid');
				sot_mail_send(params, this.sot_clickSendCallBack.bind(this), this.clickSendMailFailureCallBack.bind(this));
				return;
			}
			//SOT Add End
			mail_send(params, this.clickSendMailCallBack.bind(this), this.clickSendMailFailureCallBack.bind(this));
		}
	},
	
	// 如果用户没有填写主题，并且有上传附件，那么将第一个附件的名称作为主题，如果是照片，再做特殊处理
	filename2Subject: function(fname) {
		if(!fname) return false;
		try {
			var _subject = DOM.compose_subject.value;
			if (_subject.blank()) {
				var _sj = fname, _sub = _sj.split('.'), _sjl = _sj.toLowerCase();
				_sub = _sub.slice(0, _sub.length - 1);
				_subject = _sub.join('');
				if ((_sjl.startsWith('img') || _sjl.startsWith('dsc')) && _sjl.endsWith('jpg')) {
					_subject = '照片';
				}
				DOM.compose_subject.value = _subject;
			}
		} catch(e) { }
	},

	_content2text : function(content) {
		if (this.defaulteditor == "text") {
			return content;
		} else {
			return content.replace(/\&nbsp\;/g, " ").replace(/<br/g, "\n<br")
					.replace(/<\/p><p>/g, "</p>\n<p>").stripTags();
		}
	},

	getSendEmail2ArrayList : function(emailStr, isTo) {
		if (isTo && emailStr.strip() == "") {
			_dialog.alert({info: '请填写收件人地址！'});
			return false;
		}
		emailStr = toTrimDBC(emailStr).replace(/;/ig, ',').replace(/；/ig, ',').replace(/，/ig, ',');
		var al = emailStr.split(',');
		var tmp = [];
		if (emailStr.blank()) {
			return [];
		}
		for (var i = 0; i < al.length; i++) {
			if (al[i].blank()) {
				continue;
			}
			var _item = al[i].strip();
			var _flag = false;
			var item_mail = '';
			contactCates.each(function(item) {
				if (_item == item.name) {
					_flag = true;
					var _tp = [];
					contactLists.each(function(__item) {
						if(item.contactid.include(__item.id)) {
							_tp.push(__item.email);
						}
					});
					item_mail = _tp.join(',');
				}
			});
			if(_item == '最近联系人') {
				_flag = true;
				var _tp = [];
				recentLists.each(function(item) {
					_tp.push(item.email);
				});
				item_mail = item_mail == '' ? _tp.join(',') : item_mail + ',' + _tp.join(',');
			}
			if(_flag) {
				tmp.push(item_mail);
			} else {
				var __al = '';
				if (al[i].split('<').length > 1 && al[i].split('>').length > 1) {
					var tmp1 = al[i].split('<');
					var tmp2 = tmp1[1].split('>');
					__al = tmp2[0];
				}
				__al = __al == '' ? al[i] : __al;
				if (this.getCheckEmailAddress(__al.strip())) {
					tmp.push(al[i].strip());
					this.legitimate = true;
				} else {
					this.legitimate = false;
					tmp.clear();
					return false;
				}
			}
		}
		return tmp.join(',').split(',').uniq();
	},

	getCheckEmailAddress : function(email) {
		if (email == null || email.strip() == "") {
			_dialog.alert({info: '邮件地址格式不正确，请重新填写！'});
			return false;
		}
		if (!IsEmail(email)) {
			_dialog.alert({info: '邮件地址格式不正确，请重新填写！'});
			return false;
		} else {
			return true;
		}
	},
	//SOT Add SOT按钮点击后的CallBack事件
	sot_clickSendCallBack : function( ret ) {
		removeDiv4Sending();
		Tips.hide();
		this.thisCurrentMailisSending = false;
		if (ret.is_success == true ) {
			if (this.thisIsDraftToWriteMail || this.userIsSaveDraft) {
				var params = {
					src : mailList.currentFolder,
					dest_id : -1,
					mails : this.draftAutoSaveId
				};
				mail_move(params);
			}
			var t = new Template( SOTMailSuccessTemplate );
			var data = new Array;
			var emailList = '';
			var optionList = '';
			var autoSaveSendEmail = '';
			var promptGift = '';
			var tmpMailList;
			tmpMailList = this.stripEqualValue(this.sendSucMailList);
			data[ "sot_subject" ] = this.subject;
			data[ "sot_sendtime" ] = sendontime.getDisplayDate();
			emailList += '<span>'; 
			for (var i = 0; i < tmpMailList.length; i++) {
				emailList += '<li>' + tmpMailList[i] + ' </li>';
			}
			emailList += ' </span>';
			if (mailCfgClass.getProfileContent().autosavesendmail) {
				var save_list = ret.save_list;  
				var savelen = save_list.length;
				if(savelen > 0){
					autoSaveSendEmail = '<li><input type="checkbox" class="s_succ_group"> 将本次被保存成功的联系人添加到通讯组中。</li>';
				    autoSaveSendEmail += '<li id="groupel" style="display:none"></li>';
				}
			} else {
				autoSaveSendEmail = '<br /><input type="checkbox" class="s_set_send_save" value="" /> 以后都将我发过信的联系人自动添加到地址簿';
			}
			if(ret.ad) {
				promptGift = ret.ad;
			}
			
			data['emailList'] = emailList;
			data['optionList'] = optionList;
			data['autoSaveSendEmail'] = autoSaveSendEmail;
			data['promptGift'] = promptGift;
			$("compose.sendinfo").innerHTML = t.evaluate(data);
			this.mailIsSuccess = true;
			hiddenAllPanel();
			DOM.sendSuc.show();
			changePanel("sendSuc");
			if (mailCfgClass.getProfileContent().autosavesendmail) {
				this.sendSuccSaveMailList(tmpMailList);
			}
		}else {
			writemail.userIsSaveDraft = false;
			mailUploadFile.init();
			// 为上传附件创建form表单
			mailUploadFile.createForm();
			if( ret.is_sot ==1 && ret.code == -2 ) {
				_dialog.alert({info: '您已经设置了10封定时邮件了！'});
			} else if ( ret.is_sot == 1 ) {
				_dialog.alert({info: '由于网络原因，您的邮件没有发送成功，请重试！'});
			}
			else {
                    //Prompt Mail
                    var desc_str = null, link_str = null;
        			var t = new Template(SmtpPromptTemplete);
        			var data = new Array;
                    data[ 'link_prompt' ] = 'http://mail.sohu.com/info/policy/';
                    data[ 'str_prompt' ] = '未知错误，请参考我们的错误信息';
                    var ret_str = ret.error.split( '|' );
                    if( ret_str.length > 1 )
                    {
                        data[ 'str_prompt' ] = ret_str[ 0 ];
                        data[ 'str_errcode' ] = ret.code;
                        data[ 'link_prompt' ] = ret_str[ 1 ];
                        this.create_smtpPromptMask();
                        Element.insert($('sohuMailMain'), {bottom: t.evaluate( data )});
                        //getWindowDimensions<--global functions :158
                        var screen = getWindowDimensions();
                        var _x = parseInt( screen.win_width -  600 )/2;
                        var _y = parseInt( screen.win_height - 300 )/3;
                        try{
                        $( 'del_group_prompt_panel_one' ).parentNode.setStyle({left:_x+"px",top:_y+"px"});
                        }
                        catch( e ){
                        }
                        try{
                             var s = $('smtp_prompt_panel').getElementsByClassName( "justfinder" );
                             s[0].setStyle({left:_x+"px",top:_y+"px"});
                        }
                        catch( e ){ }
                    }
			}
			writemail.AutoStore.start();
			return;
		}
		sendontime.initUIString();
	},
	//SOT Add End
	
	clickSendMailCallBack : function(ret) {
        //
        //如果发送的时候是新手上路,那么不管发送成功与否,都应该给积分.
        //并且刷新一下现在的缓存.
        if(this.is_tourial) {
        	var __tou__ = setTimeout(function(ret){
				clearTimeout(__tou__);
                __tou__ = null;
				try {
					get_newbee_type('complete_mission', 'write_letter', 1);
				} catch(e) {}
            }, 100);
        }

		// mail_signature=0;
		removeDiv4Sending();
		Tips.hide();
		this.thisCurrentMailisSending = false;
		if (ret.is_success) {
			// 发送成功之后，如果是回复、转发的邮件，将缓存列表中的status状态改变
			try {
				if (this.original_id) {
					var _type = this.draft_type == 1 ? 'have_forward' : 'have_reply';
					mailList.setMiscMailCache(this.original_id, _type);
				}
			} catch(e) {}
			
			var atsv = mailCfgClass.getProfileContent().autosavesendmail;
			var t = new Template(sendSucAddContactListTemplate);
			var data = {};
			var emailList = [];
			var optionList = [];
			var autoSaveSendEmail = '';
			var promptGift = '';
			var tmpMailList;
			tmpMailList = this.stripEqualValue(this.sendSucMailList);
			this.tmpMailList = tmpMailList;
			tmpMailList.each(function(item) {
				if(!IsEmail(item, false)) return;
				emailList.push('<dd>' + item + ' &nbsp;&nbsp;</dd>');
				if (this.isNotInContactList(item)) {
					optionList.push('<li><a hidefocus="true" id="save_succ_'+ item +'" class="s_succ_save" eid="'+ item +'" href="javascript:;"> 添加到地址本 </a></li>');
				} else {
					optionList.push('<li>&nbsp;&nbsp;</li>');
				}
			}.bind(this));
			if (atsv) {
				var save_list = ret.save_list;
				var savelen = save_list.length;
				if (save_list && save_list.length > 0) {
					this.save_addr_list = [];
					save_list.each(function(item) {
						this.save_addr_list.push(item.id);
					}.bind(this));
				}
				if(savelen > 0){
					autoSaveSendEmail = '<li"><input type="checkbox" class="s_succ_group"> 将本次被保存成功的联系人添加到通讯组中。</li>';
				    autoSaveSendEmail += '<li id="groupel" style="display:none"></li>';
				}
			} else {
				autoSaveSendEmail = '<br /><input type="checkbox" class="s_set_send_save" value="" /> 以后都将我发过信的联系人自动添加到地址簿';
			}
			if(USE_SYS.name == 'sohu') getScoreInfo();
			
			data['emailList'] = emailList.join('');
			data['optionList'] = optionList.join('');
			data['autoSaveSendEmail'] = autoSaveSendEmail;
			$('compose.sendinfo').innerHTML = t.evaluate(data);
			hiddenAllPanel();
			this.mailIsSuccess = true;
			changePanel('sendSuc');
			if(atsv) {
				this.sendSuccSaveMailList(ret.save_list);
			}
			var save_recent = ret.addr_list ? ret.save_list.concat(ret.addr_list) : ret.save_list;
			this.addRecentLists(save_recent);
		} else {
			writemail.userIsSaveDraft = false;
			_dialog.alert({info: ret.message});
			writemail.AutoStore.start();
			return;
		}
		// 清除掉会话模式下发件箱列表的缓存
		try {
			mailConference.clearListCache(3);
		} catch(e) {}
	},
	
	// 将发送成功的联系人加入到最近联系人组中
	addRecentLists: function(obj) {
		var recent_tmp_hash = {};
		recentLists.each(function(item) {
			recent_tmp_hash[item.email] = item.id;
		});
		var _new_obj = [];
		obj.each(function(item) {
			if(!recent_tmp_hash[item.email]) _new_obj.push(item);
		});
		recentLists = _new_obj.concat(recentLists).slice(0, mailAddressClass.rectLimit);
		// recentLists = recentLists.concat(_new_obj);
		var _tmp_obj = [];
		_new_obj.each(function(item) {
			var adiv = mailAddressClass.createListItem(item);
			_tmp_obj.push(adiv);
			// mailAddressClass.mailRecentListDOM.push(adiv);
		});
		mailAddressClass.mailRecentListDOM = _tmp_obj.concat(mailAddressClass.mailRecentListDOM).slice(0, mailAddressClass.rectLimit);
	},

	clickSendMailFailureCallBack : function() {
		try {
			Tips.hide();
			if (this.thisCurrentMailisSending) {
				this.thisCurrentMailisSending = false;
				_dialog.alert({
					info: '由于网络原因，您的邮件没有发送成功，请重试！'
				});
				writemail.AutoStore.start();
			}
		} catch(e) {}
		try {
			// mail_send_e.init(['compose.wto'],6,UID+genKeyCode());
		} catch(e) {}
		return;
	},

	autoSaveSendMailList : function(inputObj, mList, click) {
		if (inputObj.checked) {
			var params = {
				autosavesendmail : true
			};
			if(!click || typeof(click) == "undefined") {
				click = false;
			}
			var tmpMailList = this.stripEqualValue(this.sendSucMailList);
			this.sendSuccSaveMailList(tmpMailList, click);
			profile_set(params, this.autoSaveSendMailListCallBack.bind(this, true));
			$('autoSaveSendEmail').hide();
		}
	},

	autoSaveSendMailListCallBack : function(autosavesendmail, ret) {
		if (ret.is_success) {
			mailCfgClass.getProfileContent().autosavesendmail = autosavesendmail;
			_dialog.alert({info: '配置已生效，以后联系人将自动添加到地址簿。'});
		}
	},

	sendSuccSaveMailList : function(tmpMailList, click) {
		contactLists = contactLists.concat(tmpMailList);
		tmpMailList.each(function(item) {
			var adiv = mailAddressClass.createListItem(item);
			mailAddressClass.mailAddrListDOM.push(adiv);
			mailAddressClass.setRecentItemNick(item);
		});
		if(!click) {
			try {
				var _ol = $('optionList');
				var l = _ol ? $A(_ol.getElementsByTagName('li')) : null;
			} catch(e) {}
			if(l) {
				for (var j = 0; j < l.length; j++) {
					l[j].innerHTML = '&nbsp;';
				}
			}
		}
	},
	// 当发信完成向后台添加联系人的时候，判断当前联系人所用的昵称是否存在，如果存在依次向后累加0，1，2这样的数字
	filterAddr: function(nick) {
		var _nick = nick;
		var index = 0;
		var flag = false;
		var _filter_addr = function(n) {
			for(var i=0;i<contactLists.length;i++) {
				if(contactLists[i].name == n) {
					_nick = nick + index;
					index ++;
					flag = true;
					break;
				} else {
					flag = false;
				}
			}
			if(flag) _filter_addr(_nick);
		};
		_filter_addr(nick);
		return _nick;
	},

	stripEqualValue : function(arr) {
		if(!arr || arr.length == 0) return [];
		var _tmp = [];
		arr.each(function(item) {
			if(item.indexOf('<') != -1 && item.indexOf('>') != -1) {
				_tmp.push(item.substring(item.indexOf('<') + 1, item.indexOf('>')).toLowerCase());
			} else {
				_tmp.push(item.toLowerCase());
			}
		});
		return _tmp.uniq();
	},

	isNotInContactList : function(arr) {
		if (!Object.isArray(contactLists)) {
			return;
		}
		var _flag = true;
		try {
			contactCates.each(function(item){
				if (item.name == arr) _flag = false;
			});
		} catch(e) { }
		try {
			contactLists.each(function(item){
				if (item.email == arr) _flag = false;
			});
		} catch(e) { }
		return _flag;
	},

	clickSaveMail : function(userIF) {
		if (global_flag) {
			return;
		}
		var sotIF = 0;
		if(userIF == 'userclick' && sendontime.isChecked()) {
			// var sotsavedraft = confirm( "该邮件是定时发送邮件，如果您要将其保存为草稿，系统会将定制时间清空。您确定要保存为草稿吗？" );
			_dialog.confirm({info: '该邮件是定时发送邮件，如果您要将其保存为草稿，系统会将定制时间清空。您确定要保存为草稿吗？', click: function() {
				change_panel_flag = true;
				writemail.clickSaveMail(userIF);
				change_panel_flag = false;
			}});
			if(!change_panel_flag) return false;
			if (sendontime.getDBID() > 0) {
				sotIF = 1;
			} else {
				sotIF = 0;
			}
		}
		
		var ufile = [];
		mailUploadFile.FILES_INFOS.each(function(item) {
			if(item.success) ufile.push(item.id);
		});
		
		var html_content = '', text_content = '';
		if(this.defaulteditor == 'html') {
			html_content = this.getContentInput();
			text_content = html_content.stripTags();
		} else {
			text_content = this.getContentInput();
			html_content = text_content.replace(/\n/ig, '<br />');
		}
		var _env = {
			attach: ufile,
			// reply_id: 0,
			// forward_id: 0,
			original_id: this.original_id,
			draft_type: this.draft_type,
			message_id: this.message_id,
			references: this.references,
			reply_to: this.reply_to,
			in_reply_to: this.in_reply_to,
			mail_followup_to: this.mail_followup_to,
			
			thread: this.thread
		};
		var params = {
			id : this.draftAutoSaveId,
			// id: this.deleteSaveId,
			is_send: 0,
			is_html : (this.defaulteditor == "text") ? 0 : 1,
			to : DOM.compose_wto.value,
			cc : DOM.compose_wcc.value,
			bcc : DOM.compose_wbcc.value,
			subject : DOM.compose_subject.value,
			html: html_content,
			text: text_content,
			env: Object.toJSON(_env)
		};
		
		this.userIsSaveDraft = true;
		if (userIF == 'userclick') {
			if (!this.checkFileUploading()) {
				DOM.compose_subject.focus();
				return false;
			}
			createShadowDiv();
			// createDiv4Saving();
			// Tips.show("邮件正在保存中，请稍候...");
			Tips.text = '正在保存...';
			this.AutoStore.stop();
			this.thisCurrentMailisSending = true;
			if( sotIF == 1 )
			{
				params[ "sot_id" ] = sendontime.getDBID();
				params[ "sot_delpath" ] = sendontime.getFilePath();
				sot_draft_save( params, this.clickSaveMailCallBack.bind(this), this.clickSaveMailFailureCallBack.bind(this) );
			}
			else
			{
				mail_save(params, this.clickSaveMailCallBack.bind(this), this.clickSaveMailFailureCallBack.bind(this));
			}
		} else {
			if(mailUploadFile.uploading) return false;
			if (this.isContentChanged() && !mailUploadFile.uploading) {
				mail_save(params, this.autoStoreCallBack.bind(this));
			}
		}
	},

	autoStoreCallBack : function(ret) {
		// var callbackObj = response.responseText.evalJSON();
		if (typeof ret == 'object') {
			this.draftAutoSaveId = ret.id;
			this.to = DOM.compose_wto.value;
			this.cc = DOM.compose_wcc.value;
			this.bcc = DOM.compose_wbcc.value;
			this.subject = DOM.compose_subject.value;
			this.content = this.getContentInput();
			this.attDivContent = DOM.uploadInfoDIV.innerHTML;
			try {
				var _mom = $('mail.operate.message');
				_mom && (_mom.innerHTML = strfTime(+new Date()) + '保存草稿');
			} catch(e) {}
			this.setAutoStored(true);
			this.AutoStore.restart();
		}
	},

	clickSaveMailCallBack : function(ret) {
		removeDiv4Sending();
		Tips.hide();
		// 清除掉会话模式下草稿箱列表的缓存
		try {
			mailConference.clearListCache(2);
		} catch(e) {}
		this.thisCurrentMailisSending = false;
		if (typeof ret == 'object') {
			this.draftAutoSaveId = ret.id;
			this.mailIsSave = true;
			this.setAutoStored(true);
			this.AutoStore.stop();
			messageInfo = '邮件已保存到草稿箱';
			changePanel('mailList', 2);
		} else {
			_dialog.alert({info: ret.message});
		}
	},
	
	clickSaveMailFailureCallBack : function() {
		removeDiv4Sending();
		Tips.hide();
		if (this.thisCurrentMailisSending) {
			this.thisCurrentMailisSending = false;
			_dialog.alert({info: '由于网络原因，您的邮件没有发送成功，请重试！'});
			writemail.AutoStore.start();
		}
		return;
	},

	clickEditorChange : function() {
		var pset = function(fmt) {
			profile_set({defaulteditor: fmt}, function(ret) {
				try {
					mailCfgClass.getProfileContent().defaulteditor = fmt;
					PROFILE.defaulteditor = fmt;
				} catch(e) {}
			});
		};
		if (this.defaulteditor == 'text') {
			try {
				this.defaulteditor = "html";
				this.content = DOM.editor_mess2.value.replace(/\n/gi, "<br />");
				Editor.setContent(this.content);
				DOM.compose_mess1.show();
				DOM.compose_mess2.hide();
			} catch (e) {}
			try {
				pset('html');
			} catch(e) {}
		} else {
			var self = this,
			pfunc = function() {
				self.defaulteditor = "text";
				// this.content = Editor.getContent().replace(/\&nbsp\;/gi, '').replace(/<br/gi, '\n<br').replace(/<\/p>/gi, '<\/p>\n').stripTags();
				self.content = Editor.getContent().replace(/\&nbsp\;/gi, '').replace(/<br/gi, '\n<br').stripTags();
				DOM.editor_mess2.value = self.content;
				DOM.compose_mess2.show();
				DOM.compose_mess1.hide();
				try {
					DOM.write_letter_operate.visible() && self.scrollAnimation.slideUp(DOM.write_letter_operate, 70);
				} catch(e) {}
				try {
					pset('text');
				} catch(e) {}
			};
			try {
				_dialog.confirm({info:'将此邮件转换为纯文本格式将会遗失某些格式化设置并会删除已插入的项目。确定要继续吗？', click: function() {
					pfunc();
				}});
			} catch (e) {}
		}
	},

	_clickEditorChangeCallBack : function(ret) {
		if (ret.is_success) {
			mailCfgClass.setProfileContent();
		}
	},
	
	addSign: function() {
		var _p = mailCfgClass.getProfileContent();
		if((!_p.signature || _p.signature.stripTags() == '') && (!_p.image_signature || !_p.image_signature_name)) return false;
		var _html = [];
		if (this.defaulteditor != 'text') {
			_html.push('<br /><br /><br /><br /><br /><br /><br /><br />');
			_html.push('<div><table cellspacing=0 cellpadding=0 style="border:0;margin:0px;padding:0px;"><tbody><tr style="vertical-align:top;"><td style="margin:0px 4px;">');
			_html.push((_p.image_signature && _p.image_signature_name && _p.image_signature_name.strip() != '') ? '<img src="' + SIGN_ROOT + '/' + _p.image_signature_name + '.jpg" style="border:0;margin:0px 4px;" />' : '');
			_html.push('</td><td style="margin:0px 4px;">');
			_html.push(_p.signature ? _p.signature : '');
			_html.push('</td></tr></tbody></table></div>');
		} else {
			_html.push('\n\n\n\n\n\n\n\n');
			_html.push(_p.signature ? _p.signature.replace(/\&nbsp\;/gi, '').replace(/<br/gi, '\n<br').stripTags() : '');
		}
		var _c = _html.join('');
		this.setContentInput(this.getContentInput()+_c);
	},
	
    addSignInWriteMail : function() {
		if (!mailCfgClass.getProfileContent().signature|| mailCfgClass.getProfileContent().signature.strip() == "") {
			_dialog.alert({info: '您的签名为空，请先设置签名！'});
			return;
		}
		if (this.defaulteditor != "text") {
			try {
				if(!mailCfgClass.getProfileContent().image_signature){
					var currentSign = "<br /><br /><br /><br /><div id='addMailSign'><br /><div id='textSign'>"
					+mailCfgClass.getProfileContent().signature+ "</div></div>";
				} else {
					if (mailCfgClass.getProfileContent().image_signature_name) {
						var currentSign = "<br /><br /><br /><br /><div id='addMailSign'><br /> <div id='imageSign'><img src="+SIGN_ROOT + "/" + mailCfgClass.getProfileContent().image_signature_name + ".jpg?"+Math.random()+"  style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>"
						+"<div style='margin: 12px 28px 28px 10px; float: left;'>" +mailCfgClass.getProfileContent().signature
						+"</div></div><div style='clear:both;'></div></div>";
					}else{
						var currentSign = "<br /><br /><br /><br /><div id='addMailSign'><br /> <div id='imageSign'><img src='"+ MailConst.ALL+"/demo.jpg'   style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>" 
						+"<div style='margin: 12px 28px 28px 10px; float: left;'>"+mailCfgClass.getProfileContent().signature+
						"</div></div></div>";
					}
				}
			} catch(e) {}
		} else {
			var currentSign = "\n\n\n\n\n \n "+ mailCfgClass.getProfileContent().signature;
		}
		var add_mail_sign = Editor.c().document.getElementById("addMailSign");
		var personal_sign = Editor.c().document.getElementById("personalSign");
		var text_sign = Editor.c().document.getElementById("textSign");
		var image_sign = Editor.c().document.getElementById("imageSign");
		var mail_content = Editor.c().document.getElementById("mailcontent");
		if (add_mail_sign && add_mail_sign != null) {
			try {
				if (!mailCfgClass.getProfileContent().image_signature) {
					if (!personal_sign) {
						add_mail_sign.innerHTML = "<br /><div id='textSign'>" + mailCfgClass.getProfileContent().signature + "</div>";
					} else {
						var content = "<div id='textSign'>" + mailCfgClass.getProfileContent().signature + "<br /></div>";
						if(!text_sign) add_mail_sign.innerHTML = content + add_mail_sign.innerHTML;
						/*
						Element.insert(personal_sign, {
							before: content
						});
						*/
					}
				} else {
					if (!personal_sign) {
						if (mailCfgClass.getProfileContent().image_signature_name) {
							add_mail_sign.innerHTML = "<br /> <div id='imageSign'><img src=" +SIGN_ROOT + "/" +  mailCfgClass.getProfileContent().image_signature_name +".jpg?"+Math.random()+ "  style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>" +
							"<div style='margin: 12px 28px 28px 10px; float: left;'>" +
							mailCfgClass.getProfileContent().signature +
							"</div><div style='clear:both;'></div></div>";
						} else {
							add_mail_sign.innerHTML = "<br /> <div id='imageSign'><img src='" + MailConst.ALL + "/demo.jpg' style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>" +
							"<div style='margin: 12px 28px 28px 10px; float: left;'>" +
							mailCfgClass.getProfileContent().signature +
							"</div></div>";
						}
					} else {
						var content='';
						if (mailCfgClass.getProfileContent().image_signature_name) {
							content = "<br /><div id='imageSign'><img src=" + SIGN_ROOT + "/" +mailCfgClass.getProfileContent().image_signature_name +".jpg?"+Math.random()+"  style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>" +
							"<div style='margin: 12px 28px 28px 10px; float: left;'>" +
							mailCfgClass.getProfileContent().signature+
							"</div></div>";
							// Element.insert(Editor.c().document.getElementById("personalSign"), {before: content});
							if(!image_sign) add_mail_sign.innerHTML = content + add_mail_sign.innerHTML;
						}
						else {
							content = "<br /><div id='imageSign'><img src='" + MailConst.ALL + "/demo.jpg'   style='width:148px;height:106px;margin: 15px 4px 8px 15px; float: left; display: inline;'/>" +
							"<div style='margin: 12px 28px 28px 10px; float: left;'>" +
							mailCfgClass.getProfileContent().signature +
							"</div></div>";
						}
						//Element.insert(Editor.c().document.getElementById("personalSign"), {before: content});
					}
				}
			} catch(e) {}
		} else {
            if (mail_content) {
				Element.insert(mail_content, {
					before: currentSign
				});
			} else {
				this.setContentInput(this.getContentInput() + currentSign);
			}
		}
	},
	
	draft2Write : function(_params) {
		if(!listenVolume()) return false;
		this.draftAutoSaveId = _params.id;
		mail_read(_params, this.draft2WriteCallBack.bind(this));
	},

	draft2WriteCallBack : function(ret) {
		this.thisIsDraftToWriteMail = true;
		// this.draftContent = ret.display;
		this.draftAutoSaveId = ret.rowid;
        this.defaulteditor = mailCfgClass.getProfileContent().defaulteditor ? mailCfgClass.getProfileContent().defaulteditor : 'html';
		
		try {
			changeToolbarStyle('');
		} catch (e) { }
		// DOM.mail_operate_message.innerHTML = "";
		DOM.upload_iframe_content.innerHTML = "";
		mailUploadFile.init();
		// 为上传附件创建form表单
		mailUploadFile.createForm();
		
		var __to = this._getAddressList(ret.envelope.to), __cc = this._getAddressList(ret.envelope.cc), __bcc = this._getAddressList(ret.envelope.bcc);
		var _to = __to.length > 0 ? __to.join(', ') + ', ' : '';
		var _cc = __cc.length > 0 ? __cc.join(', ') + ', ' : '';
		var _bcc = __bcc.length > 0 ? __bcc.join(', ') + ', ' : '';
		DOM.compose_subject.value = ret.envelope.subject;
		DOM.compose_wto.value = _to;
		DOM.compose_wcc.value = _cc;
		DOM.compose_wbcc.value = _bcc;
		__cc.length > 0 ? DOM.mail_cc.show() : DOM.mail_cc.hide();
		__bcc.length > 0 ? DOM.mail_bcc.show() : DOM.mail_bcc.hide();
		DOM.uploadInfoDIV.innerHTML = '';
		DOM.uploadInfoDIV.hide();
		this.subject = ret.envelope.subject;;
		this.to = _to;
		this.cc = _cc;
		this.bcc = _bcc;
		this.attDivContent = DOM.uploadInfoDIV.innerHTML;
		// this.mailMiscHeaders = ret.misc_headers;
		// this._clickSave(this.is_save ? true : false);
		appendAddressBook();
		resizeWriteAreaHeight();
		try {
			Element.show(DOM.compose_wto.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling.nextSibling);
		} catch(e) {}
		try {
			if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
			if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
			DOM.top_operate_area.innerHTML = common_top_html;
			DOM.bottom_operate_area.innerHTML = common_bottom_html;
		} catch(e) {}
		try {
			// this._clickSave(this.is_save ? true : false);
		} catch(e) {}
		try {
			this.writeFunc.each(function(item, index) {
				var _item = $(item);
				if(index == 0) {
					try {
						_item.show();
						_item.style.visibility = 'visible';
					} catch(e) {}
				} else {
					try {
						_item.hide();
						_item.style.visibility = 'hidden';
					} catch(e) {}
				}
			});
		} catch(e) {}
		if (this.defaulteditor == "text") {
			// DOM.compose_editer.innerHTML = '切换为HTML';
			DOM.compose_mess1.hide();
			DOM.compose_mess2.show();
			// DOM.user_sign_area.hide();
		} else {
			// DOM.compose_editer.innerHTML = '切换为纯文本';
			DOM.compose_mess1.show();
			DOM.compose_mess2.hide();
			// DOM.user_sign_area.show();
		}
		try {
			this.initAutocomplete();
		} catch(e) {}
		// SOT Start 绑定单选框和下拉框区域
		try {
			var t2 = setTimeout(function(){
				clearTimeout(t2);
				t2 = null;
				sendontime.setCheckBox('sot_control', 'sohu_sot_container');
				sendontime.initUIString();
			}, 10);
		} catch(e) {}
		// SOT End
		try {
			RUpload.init();
		} catch(e) {}
		//SOT Add初始化一下SOT控件，这里主要避免用户从草稿箱编辑邮件时候的一个bug
//		var t1 = setTimeout(function() {
//			clearTimeout(t1);
//			t1 = null;
//			sendontime.setCheckBox( "sot_control", "sohu_sot_container" );
//			sendontime.initUIString();
//		}, 10);
		//SOT Add End
		try {
			if(!DOM.write_letter_operate) DOM.write_letter_operate = $('write_letter_operate');
			DOM.write_letter_operate.hide();
		} catch(e) {}
		hiddenAllPanel();
		DOM.composeMail.show();
		changePanel('draftToComposeMail');
		this.setContentInput(ret.display ? ret.display : '');
		var self = this;
		var __t = setTimeout(function() {
			self.content = self.getContentInput();
		}, 0);
		this.AutoStore.restart();
		
		if (ret.envelope.attach.length > 0) {
			mail_save_att({}, this._draft2WriteCallBack.bind(this, ret.envelope.attach));
		}
		try{
			/*
            if(DOM.composeMail.lastChild.id != "panel_div"){
                Element.insert(DOM.composeMail, {bottom: panel_str});
            }
            */
        } catch( e ){}
		DOM.compose_wto.focus();
		mail_send_e.init(['compose.wto'],6,UID+genKeyCode());
	},
	//SOT Add 为了避免和原邮件之间的冲突，这里重写了Draft2WriteCallBack,最好能把和原邮件相同的部分抽象一下，分离出去相同的部分
	sotDraft2WriteCallBack: function(ret) {
		this.thisIsDraftToWriteMail = true;
		this.draftContent = ret.display;
        this.defaulteditor = mailCfgClass.getProfileContent().defaulteditor ? mailCfgClass.getProfileContent().defaulteditor : 'html';
		try {
			changeToolbarStyle('');
		} catch (e) {}
		DOM.upload_iframe_content.innerHTML = '';
		mailUploadFile.init();
		// 为上传附件创建form表单
		mailUploadFile.createForm();
		var __to = this._getAddressList(ret.envelope.to), __cc = this._getAddressList(ret.envelope.cc), __bcc = this._getAddressList(ret.envelope.bcc);
		var _to = __to.length > 0 ? __to.join(', ') + ', ' : '';
		var _cc = __cc.length > 0 ? __cc.join(', ') + ', ' : '';
		var _bcc = __bcc.length > 0 ? __bcc.join(', ') + ', ' : '';
		DOM.compose_subject.value = ret.envelope.subject;
		DOM.compose_wto.value = _to;
		DOM.compose_wcc.value = _cc;
		DOM.compose_wbcc.value = _bcc;
		__cc.length > 0 ? DOM.mail_cc.show() : DOM.mail_cc.hide();
		__bcc.length > 0 ? DOM.mail_bcc.show() : DOM.mail_bcc.hide();
		DOM.uploadInfoDIV.update('');
		DOM.uploadInfoDIV.hide();
		this.subject = ret.envelope.subject;
		this.to = _to;
		this.cc = _cc;
		this.bcc = _bcc;
		this.attDivContent = DOM.uploadInfoDIV.innerHTML;
		// this.mailMiscHeaders = ret.misc_headers;
		// this._clickSave(this.is_save ? true : false);
		appendAddressBook();
		resizeWriteAreaHeight();
		try {
			Element.show(DOM.compose_wto.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling);
            //sot状态下不支持单封发送
			Element.hide(DOM.compose_wto.nextSibling.nextSibling.nextSibling);
		} catch(e) {}
		// 改变界面UI元素
		try {
			if(!DOM.write_letter_operate) DOM.write_letter_operate = $('write_letter_operate');
			DOM.write_letter_operate.hide();
		} catch(e) {}
		hiddenAllPanel();
		try {
			if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
			if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
			DOM.top_operate_area.innerHTML = common_top_html;
			DOM.bottom_operate_area.innerHTML = common_bottom_html;
		} catch(e) {}
		try {
			// this._clickSave(this.is_save ? true : false);
		} catch(e) {}
		try {
			this.writeFunc.each(function(item, index) {
				var _item = $(item);
				if(index == 0) {
					try {
						_item.show();
						_item.style.visibility = 'visible';
					} catch(e) {}
				} else {
					try {
						_item.hide();
						_item.style.visibility = 'hidden';
					} catch(e) {}
				}
			});
		} catch(e) {}
		DOM.composeMail.show();
		changePanel('draftToComposeMail');
		this.setContentInput(ret.display);
		this.content = this.getContentInput();
		this.AutoStore.restart();
		if (this.defaulteditor == "text") {
			DOM.compose_mess1.hide();
			DOM.compose_mess2.show();
		} else {
			DOM.compose_mess1.show();
			DOM.compose_mess2.hide();
		}
        try {
			RUpload.init();
		} catch(e) {}
		sendontime.setCheckBox('sot_control', 'sohu_sot_container');
		sendontime.initUIString();
		sendontime.setStartTime(ret.sot_date, 1);
		sendontime.setSelect(true);
		if ( ret.sot_back == 1 ) {
			$('saveCheckbox1').checked = true;
		} else {
			$('saveCheckbox1').checked = false;
		}
		sendontime.setFilePath(ret.sot_file);
		sendontime.setDBID(ret.sot_id); 
		sendontime.setMod('1');
		var ats = ret.envelope.attach;
		this._draft2WriteCallBack(ats, ret);
		try {
			/*
            if( DOM.composeMail.lastChild.id != "panel_div" ){
                Element.insert(DOM.composeMail, { bottom : panel_str } );
            }
            */
        } catch( e ){}
		DOM.compose_wto.focus();
	},
	//SOT Add End
	_draft2WriteCallBack : function(id_list, ret) {
		if(!Object.isArray(id_list)) return false;
		if(id_list.length == 0) return false;
		var _tmp = [];
		ret.each(function(item) {
			if(id_list.include(item.id)) _tmp.push(item);
		});
		mailUploadFile.createInitInfo(_tmp);
		this.attDivContent = $("uploadInfoDIV").innerHTML;
	},

	_getAddressList : function(addrlist) {
		var rec = [];
		addrlist.each(function(item) {
			if(item[0] && item[0] != '') {
				!item[1].blank() ? rec.push('"' + item[0] + '"' + '<' + item[1] + '>') : rec.push(item[0]);
			} else {
				rec.push(item[1]);
			}
		});
		return rec;
	},

	_clickSave : function(isChecked) {
		try {
			$('saveCheckbox1').checked = isChecked;
			$('saveCheckbox2').checked = isChecked;
		} catch(e) {}
	},

	exit : function() {
		try {
			if (this.mailIsSuccess || this.mailIsSave) {
				this._clear();
				return true;
			} else {
				if (this.isChanged() || this.thisCurrentMailisSending) {
					return false;
				} else {
					this._clear();
					return true;
				}
			}
		} catch(e) {
			return false;
		}
	},

	AutoStore : {
		start : function() {
			try {
				if (mailCfgClass.getProfileContent().autosavewritemail) {
					IntervalConst.autoStore = mailCfgClass.getProfileContent().autosavewritemail * 60;
				}
			} catch(e) {}
			this.excuter = new PeriodicalExecuter(function() {
				clickStore();
			}, IntervalConst.autoStore);
		},
		stop : function() {
			if (this.excuter) {
				this.excuter.stop();
			}
		},
		restart : function() {
			this.stop();
			this.start();
		}
	},
	setAttachmentChanged : function(_isChanged) {
		this.attachmentChanged = _isChanged;
	},
	setAutoStored : function(_isStored) {
		this.autoStored = _isStored;
	},
	isHtmlEditor : function() {
		return this.defaulteditor == "html";
	},
	getContentInput : function() {
		if (this.defaulteditor != "text") {
			try {
				if(Editor && typeof Editor.getContent == 'function') {
					return Editor.getContent();
				} else {
					return '';
				}
			} catch(e) {
				return '';
			}
		} else {
			try {
				return DOM.editor_mess2 ? DOM.editor_mess2.value : '';
			} catch(e) {
				return '';
			}
		}
	},

	setContentInput : function(_content) {
		if (this.defaulteditor != "text") {
            this.content = _content;
			return Editor.setContent(_content);
		} else {
			var _e = DOM.editor_mess2 ? DOM.editor_mess2 : $('editor.mess2');
			return _e.value = _content.replace(/\&nbsp\;/gi, '').replace(/<br/gi, '\n<br').stripTags();
		}
	},
	isChanged : function() {
		return this.isContentChanged();
	},
	isContentChanged : function() {
		var cp_to = this._notEqual(DOM.compose_wto.value, this.to),
			cp_cc = this._notEqual(DOM.compose_wcc.value, this.cc),
			cp_bcc = this._notEqual(DOM.compose_wbcc.value, this.bcc),
			cp_sub = this._notEqual(DOM.compose_subject.value, this.subject),
			cp_ct = this._notEqual(this.getContentInput(), this.content),
			cp_fl = this._notEqual(DOM.uploadInfoDIV.innerHTML, this.attDivContent);
		return (cp_to || cp_cc || cp_bcc || cp_sub || cp_ct || cp_fl);
	},
	storedIF : function() {
		return this._notEqual(this.getContentInput(), "");
	},
	_clear : function() {
		this.AutoStore.stop();
		this.setAutoStored(false);
		DOM.compose_subject.value = "";
		DOM.compose_wto.value = "";;
		DOM.compose_wcc.value = "";
		DOM.compose_wbcc.value = "";
		uploadFileNameArray = [];
		DOM.uploadInfoDIV.innerHTML = "";
		this.setContentInput("<br />");
		/*
		if (DOM.mail_operate_message) {
			DOM.mail_operate_message.innerHTML = '';
		}
		*/
		this._initConst();
	},
	_notEqual : function(str1, str2) {
		return str1 != str2;
	},
	_F : function(elementid) {
		if ($(elementid)) {
			return $F(elementid);
		}
		return "";
	},
	// 抄送，密送功能事件
	cc_toggle : function(click_id, input_id) {
		if ($(click_id).visible()) {
			$(click_id).hide();
		} else {
			$(click_id).show();
			$(input_id).focus();
		}
	},
                 //漂亮的错误提示关闭 Mail Prompt
    remove_smtpPromptPanel : function(){
                                 try{
                                     $( 'div4SmtpPrompt' ).remove();
                                 }catch( e ){}
                                 try{
                                     $( 'smtp_prompt_panel' ).remove();
                                 }catch( e ){}
                             },
                             //漂亮的遮罩 Mail Prompt
    create_smtpPromptMask : function(){
                                var h = $('nav').getHeight() + $( 'composeMail').getHeight() + 70;
                                var div = '<div id="div4SmtpPrompt" style="background:#CCCCCC;filter:Alpha(opacity=30);-moz-opacity:0.30;position:absolute;top:0px;left:0px;width:100%;height:'+ h +'px;z-index:9999;"><span> &nbsp; </span></div>';
                                Element.insert($('sohuMailMain'), {bottom: div});
                                Element.setStyle($('div4SmtpPrompt'), {filter:'Alpha(opacity=30)',opacity:0.3,mozOpacity:0.3,khtmlOpacity:0.3});
                        },
						
	// 添加用户个性签名
	changeSign: function(doc) {
		if (this.signlist && this.signlist.length > 0) {
			this.personalitysign = this.signlist[0];
			this.signlist = this.signlist.without(this.signlist[0]);
			this.appendSign(doc);
		} else {
			this.randomSign(doc);
		}
	},
	randomSign: function(doc) {
		_defun('/sign/act/RandomSign', 'post', {}, this.randomSignCallBack.bind(this, doc));
	},
	randomSignCallBack: function(doc, transport) {
		this.signlist = transport.signlist.split('|');
		this.personalitysign = this.signlist[0];
		this.signlist = this.signlist.without(this.signlist[0]);
		this.appendSign(doc);
	},
	appendSign: function(doc) {
		var E = null;
		if(!doc) {
			E = Editor;
		} else {
			E = doc;
		}
		var add_mail_sign = E.c().document.getElementById('addMailSign');
		var personal_sign = E.c().document.getElementById('personalSign');
		var image_sign = E.c().document.getElementById('imageSign');
		if (add_mail_sign && add_mail_sign != null) {
			if (!personal_sign) {
				var content = '';
				if (!image_sign) {
					content = "<br /><div id='personalSign' style='clear:both;color:#005BA2;margin-left:15px;'>" + this.personalitysign + "</div>";
				} else {
					content = "<br /><div id='personalSign' style='clear:both;color:#005BA2;margin-left:15px;'>" + this.personalitysign + "</div>";
				}
				var _div = document.createElement('div');
				add_mail_sign.innerHTML += content;
			} else {
				personal_sign.innerHTML = this.personalitysign;
			}
		} else {
			var currentSign = "<br /><br /><br /><br /><div id='addMailSign'> <br /><div id='personalSign'  style='clear:both;color:#005BA2;margin-left:15px;'>" + this.personalitysign + "</div></div>";
			// writemail.setContentInput(writemail.getContentInput() + currentSign);
			E.setContent(E.getContent() + currentSign);
		}
	},
	
	// 发送成功之后，添加联系人的提示
	// noaddr: 写信页面右侧的地址簿中，如果没有联系人，那么将会提示用户添加联系人
	saveAddr: function(el, event, noaddr) {
		if (noaddr) {
			var _e = '', _n = '';
		} else {
			var _e = el.eid ? el.eid : el.getAttribute('eid');
			if (!_e || !IsEmail(_e, false)) {
				_dialog.alert({info: '系统似乎出错了，请稍后再试~'});
				return false;
			}
			var _n = _e.split('@')[0];
		}
		var _div = document.createElement('div');
		_div.setAttribute('id', 'sign');
		var html = ['<div class="newadd" onclick="Event.stop(event);"><h4>联系人基本信息</h4>',
		           '<ul>',
		 		   '<li>昵　　称：<input type="text" class="input2" value="'+ _n +'" />',
				   '<b> *</b></li>',
				   '<li>邮箱地址：<input type="text" class="input2" value="'+ _e +'" /><b> *</b></li>',
				   '<li style="margin-bottom:10px;">添加成功后，可以到地址簿编辑联系人信息</li>',
			       '<li style="margin-left:60px;"><input value="确　定" type="button"  class="yes" />&nbsp;',
				   '<input value="取　消" type="button" class="yes" /></li>',
				   '</ul></div>'].join('');
		_div.innerHTML = html;
		menu.showMenu(el, DOM.sohuMailMain, _div, '', true, null, event);
		var l = _div.getElementsByTagName('input');
		var _nick = l[0].value, _email = l[1].value;
		var checkData = /<|>|'|;|&|#|"|'/;
            l[2].onclick = function(event) {
                var flag = false;
				_nick = l[0].value;
				_email = l[1].value;
				var _j = [{
					d: _nick.blank(),
					t: '昵称不能为空'
				}, {
					d: checkData.test(_nick),
					t: '昵称不能包含特殊字符'
				}, {
					d: mailAddressClass._check_length(_nick) > 20,
					t: '昵称的长度英文不能大于20个字符，中文不能大于10个字符'
				}];
                _j.each(function(item){
                    if (item.d && !flag) {
                        _dialog.alert({info: item.t});
                        flag = true;
                    }
                });
                if (flag) return false;
				if(!IsEmail(_email)) {
					return false;
				}
                var in_blacklist = false;
                blackLists.each(function(item){
                    if (item.email == _e) in_blacklist = true;
                });
                var confunc_sends = function(){
					var params = {
						fullname : _nick,
						nickname : _nick,
						personalemail : _email
					};
                    add_d_contact(params, function(ret) {
						if (!ret.status) {
							if (ret.errmsg == 'user is exist!') {
								_dialog.alert({info: '这个用户已经存在！'});
								return;
							} else {
								var _msg = ret.errmsg ? ret.errmsg : (ret.msg ? ret.msg : '系统错误，请稍后重试');
								_dialog.alert({info: _msg});
								return;
							}
						}
						if (mailAddressClass.checkAddrLimit([ret.msg], true)) {
							contactLists.push(ret.msg);
							var adiv = mailAddressClass.createListItem(ret.msg);
							mailAddressClass.mailAddrListDOM.push(adiv);
							mailAddressClass.setRecentItemNick(ret.msg);
						}
						try {
							el.parentNode.innerHTML = '&nbsp;';
						} catch(e) {}
						if(noaddr) {
							try {
								appendAddressBook();
							} catch(e) {}
						} else {
							try {
								_dialog.alert({
									info: '<b>联系人添加成功!</b><br /><a hidefocus="true" href="main#addressList" onclick="changePanel(\'contactList\');_dialog.close();return false;">去地址簿查看 >></a><br />该联系人已同时加入您的收信白名单，以后来自该地址的邮件都将进入您的收件箱。'
								});
							} catch(e) {}
						}
					});
					menu.closeMenu();
                };
                if (in_blacklist) {
                    _dialog.confirm({
                        info: '该地址在黑名单中，添加到地址簿会将其从黑名单中删除，是否要继续？',
                        click: function(){
                            confunc_sends();
                            var _black_list = []
                            blackLists.each(function(item){
                                if (item.email != _email) 
                                    _black_list.push(item);
                            });
                            blackLists = _black_list;
                        }
                    });
                    return false;
                }
                confunc_sends();
            };
		l[3].onclick = function(event) {
			menu.closeMenu();
		};
	},
	showgroupel : function(el, id) {
		var _el = $(id);
		try {
			if (el.checked) {
				if (!this.ggl) 
					this.ggl = this.getGroupList(_el);
				_el.show();
			} else {
				_el.hide();
			}
		} catch(e) {}
	},
	getGroupList : function(el) {
		var str = [];
		str.push(' 联系组名称：');
		str.push('<select>');
		str.push('<option value=""> 请选择 </option>');
		str.push('<option value="-1"> 新建通讯组 ...  </option>');
		contactCates.each(function(item) {
			if(item.id <= 0) return;
			var len = item.contactid == '' ? 0 : item.contactid.split(',').length;
			str.push('<option value=\"'+item.id+'\">'+item.name+'('+len+')</option>');
		});
		str.push('</select>');
		$(el).innerHTML = str.join('');
		try {
			var _se = $(el).getElementsByTagName('select')[0];
			if(_se) {
				var self = this;
				Event.stopObserving(_se, 'change');
				Event.observe(_se, 'change', function(event) {
					try {
						self.addInGroup(this);
					} catch(e) {}
				});
			}
		} catch(e) {}
		return true;
	},
	addInGroup : function(Obj) {
		try {
			hiddenAllPanel();
			DOM.addressGroupList.show();
		} catch(e) {}
		try {
			var _value = Obj.getElementsByTagName('option')[Obj.selectedIndex].value;
			if (_value != '') {
				if (_value == '-1') {
					mailAddressClass.createGroup(true, this.save_addr_list);
				} else {
					mailAddressClass.addsGroup(_value, this.save_addr_list);
					mailAddressClass.initGroup(_value, true);
				}
			}
		} catch(e) {}
	},
	
	// 是否使用分别发送功能
    isSingleSend: function(el, event){
		try {
			if(!DOM.static_cc) DOM.static_cc = $('static_cc');
			if(!DOM.static_bcc) DOM.static_bcc = $('static_bcc');
			if(!DOM.static_single) DOM.static_single = $('static_single');
		} catch(e) {}
        if (write_mail_single_flag == 0) {
            //注意SOT事件
            //如果有SOT事件,那么去掉
            try {
                if ($(sendontime._checkid).checked == true) {
					var self = this;
                    _dialog.confirm({
                        info: '定时邮件功能不能同时使用，将被取消。',
                        click: function(){
                            //如果确实要用分送,而不是SOT的话,那么....
                            $(sendontime._checkid).checked = false;
                            sendontime.hide();
                           	self.isSetSingleSend(true);
                        }
                    });
                } else {
                    this.isSetSingleSend(true);
                }
            } catch (e) { }
        } else {
            this.isSetSingleSend(false);
        }
        //将地址复制回来.
        var toTmpList = writemail.getSendEmail2ArrayList(DOM.compose_wto.value);
        var ccTmpList = writemail.getSendEmail2ArrayList(DOM.compose_wcc.value);
        var bccTmpList = writemail.getSendEmail2ArrayList(DOM.compose_wbcc.value);
        DOM.compose_wcc.value = '';
        DOM.compose_wbcc.value = '';
        DOM.mail_cc.hide();
        DOM.mail_bcc.hide();
        var ad_list = toTmpList.concat(ccTmpList).concat(bccTmpList).concat(toTmpList).uniq();
        DOM.compose_wto.value = ad_list.join(',');
    },
	
    // 是否勾选回执
    isSetDisposition : function(flag){
		try {
			if (flag) {
				$('disposition_notifier').checked = true;
				return;
			}
			$('disposition_notifier').checked = false;
		} catch(e) {}
    },
	// 是否显示分送功能
	isSetSingleSend: function(flag) {
		try {
			if(!DOM.static_cc) DOM.static_cc = $('static_cc');
			if(!DOM.static_bcc) DOM.static_bcc = $('static_bcc');
			if(!DOM.static_single) DOM.static_single = $('static_single');
		} catch(e) {}
		var _sc = DOM.static_cc.firstChild, _sbc = DOM.static_bcc.firstChild, _ss = DOM.static_single.firstChild;
		if(flag) {
			Element.addClassName(_sc, 'disabled');
			Element.addClassName(_sbc, 'disabled');
			Element.removeClassName(_sc, 's_show_mailcc');
			Element.removeClassName(_sbc, 's_show_mailbcc');
			DOM.compose_wto.previousSibling.innerHTML = '分送给：';
			_ss.innerHTML = '取消';
			write_mail_single_flag = 1;
		} else {
			Element.removeClassName(_sc, 'disabled');
			Element.removeClassName(_sbc, 'disabled');
			Element.addClassName(_sc, 's_show_mailcc');
			Element.addClassName(_sbc, 's_show_mailbcc');
			DOM.compose_wto.previousSibling.innerHTML = '收件人：';
			_ss.innerHTML = '分送';
			write_mail_single_flag = 0;
		}
	},
	
	// 设置信纸
    setLetter: function(EL, event) {
        var e = Element.hasClassName(EL, 's_letter') ? EL : Element.hasClassName(EL.parentNode, 's_letter') ? EL.parentNode : null;
        try {
            if (this.focusLetterEL && this.focusLetterEL == e) return false;
			try {
				this.focusLetterEL && Element.removeClassName(this.focusLetterEL, 'letter-focus');
			} catch(e) {}
            try {
                Element.removeClassName(e, 'letter-over');
            } catch (e) { }
            try {
                Element.addClassName(e, 'letter-focus');
            } catch (e) { }
            try {
                this.focusLetterEL = e;
            } catch (e) { }
            try {
                var _bigletter = e.bigletter ? e.bigletter : e.getAttribute('bigletter');
                if (_bigletter == 'no') {
                    noStationery2Writemail(e);
                } else {
                    addStationery2Writemail(e, _bigletter);
                }
            } catch (e) { }
        } catch (e) { }
    },
	// 设置明信片
    setPostcard: function(EL, event){
        var e = Element.hasClassName(EL, 's_postcard') ? EL : Element.hasClassName(EL.parentNode, 's_postcard') ? EL.parentNode : null;
        try {
            if (this.focusLetterEL && this.focusLetterEL == e) return false;
			try {
				this.focusLetterEL && Element.removeClassName(this.focusLetterEL, 'letter-focus');
			} catch(e) { }
            try {
                Element.removeClassName(e, 'letter-over');
            } catch (e) { }
            try {
                Element.addClassName(e, 'letter-focus');
            } catch (e) { }
            try {
                this.focusLetterEL = e;
            } catch (e) { }
        } catch (e) { }
        try {
            var _pindex = e.pindex ? e.pindex : e.getAttribute('pindex');
            _pindex = _pindex.split(',');
            var _cl = CARDLIST.evalJSON();
            changePostcardTemplate(_cl[_pindex[0]][_pindex[1]]);
        } catch (e) { }
    },
	// 设置贺卡
    setConvey: function(EL, event){
        var e = Element.hasClassName(EL, 's_convey') ? EL : Element.hasClassName(EL.parentNode, 's_convey') ? EL.parentNode : null;
        try {
            if (this.focusLetterEL && this.focusLetterEL == e) return false;
            this.focusLetterEL && Element.removeClassName(this.focusLetterEL, 'letter-focus');
            try {
                Element.removeClassName(e, 'letter-over');
            } catch (e) { }
            try {
                Element.addClassName(e, 'letter-focus');
            } catch (e) { }
            try {
                this.focusLetterEL = e;
            } catch (e) { }
        } catch (e) { }
        try {
            var _index = e.bigconvey ? e.bigconvey : e.getAttribute('bigconvey');
            custom_mail_display.updatePreviewPrompt(_index);
        } catch (e) { }
    },
    // 设置回执
    disposition_notifier_click: function(){
        write_mail_dispostion_flag = 1;
		try {
			$('disposition_notifier').checked == true ? write_mail_dispostion_flag = 1 : write_mail_dispostion_flag = 0;
		} catch(e) {}
        if (write_mail_dispostion_flag == 1) {
            try {
                if ($(sendontime._checkid).checked == true) {
                    var self = this;
                    _dialog.confirm({
                        info: '定时邮件功能不能同时使用，将被取消。',
                        click: function(){
                            $(sendontime._checkid).checked = false;
                            sendontime.hide();
                        },
                        cancelclick: function(){
                            $('disposition_notifier').checked = false;
                        }
                    });
                }
            } catch (e) { }
        }
    }
};
var writemail = new WriteMail();

// 修正中文字符HTML编码的显示问题，prototype.js中的String.unescapeHTML()函数的重写
function unescHTML(str) {
    var div = document.createElement('div');
    div.innerHTML = str.stripTags();
    return div.childNodes[0] ? (div.childNodes.length > 1 ?
      $A(div.childNodes).inject('', function(memo, node) { return memo+node.nodeValue }) :
      div.childNodes[0].nodeValue) : '';
}

function addSignInWriteMail() {
	writemail.addSignInWriteMail();
}

function addSign(){
	if ($('checkSign').checked) {
		// mail_signature = 1;
		addSignInWriteMail();
		$('checkSign').checked = true;
	} else {
		var add_mail_sign = Editor.c().document.getElementById("addMailSign");
		var image_sign = Editor.c().document.getElementById("imageSign");
		var text_sign = Editor.c().document.getElementById("textSign");
		if (add_mail_sign && add_mail_sign != null) {
			if (image_sign) {
				image_sign.parentNode.removeChild(image_sign);
			}
			if(text_sign) {
				text_sign.parentNode.removeChild(text_sign);
			}
		}
		// mail_signature=0;
		$('checkSign').checked=false;
	}
}

function autoAddtoContact(inputObj, mList, click) {
	mList = mList.split(',');
	writemail.autoSaveSendMailList(inputObj, mList, click);
}

// 发送信件操作
function clickSubmit() {
	try {
		if (!writemail.checkSendMail()) {
			return false;
		}
	} catch(e) {
		return false;
	}
	try {
		writemail.clickSendMail();
	} catch(e) {
		return false;
	}
}

//返回输入的字符串的字节数
function getStringLength(string){
	var len; 
	var i; 
	len = 0; 
	for (i=0;i<string.length;i++) { 
		if (string.charCodeAt(i) > 255) {
			len += 2;
		}else {
			len++;
		} 
	} 
	return len; 
}

function initContactCard(email, group) {
	contactCard.draw({
		email : email,
		group : group
	});
}

function clickStore(userIF) {
	writemail.clickSaveMail(userIF);
}

function clickStoreCallBack(resp) {
	writemail.setAutoStored(true);
	writemail.AutoStore.stop();
	messageInfo = '√邮件已保存到草稿箱';
	changePanel("mailList", 6);
}

function autoStoreCallBack(response) {
	var callbackObj = response.responseText.evalJSON();
	if (callbackObj && callbackObj.result) {
		$('mail.operate.message').update("" + callbackObj.time + " 保存草稿");
	}
	writemail.setAutoStored(true);
	writemail.AutoStore.restart();
}

// 切换编辑器
function clickeditor() {
	writemail.clickEditorChange();
}

function composeMailNew() {
	$('mail.cc').hide();
	$('mail.bcc').hide();
	composeMail();
}

function composeMail() {
	// writemail.writeNewMail();
	changePanel("composeMail");
}

function composeMailCallBack(response) {
	var composeContext = response.responseText.evalJSON();
	writemail.enter(composeContext);
	_composeMailCallBack_Pageview(composeContext);
	changePanel("composeMail", mailList.currentFolder);
}

// 抄送，密送输入框的显示与否
function el_toggle(id) {
	$(id).toggle();
}


function appendAddressBook() {
	if(!DOM.writeAddressArea) DOM.writeAddressArea = $("address");
	if(!DOM.writeAddr) {
		DOM.writeAddr = document.createElement('div');
		DOM.writeAddr.setAttribute('id', 'addresswritebook_ul');
		with(DOM.writeAddr.style) {
			overflowY  = 'auto';
			overflowX  = 'hidden';
			width      = '100%';
		};
		Event.observe(DOM.writeAddr, 'click', function(event) {
			try {
				writemail.addressbook_use_flag = 1;
			} catch(e) {}
		});
	}
	DOM.writeAddressArea.appendChild(DOM.writeAddr);
	DOM.writeAddr.innerHTML = addressBookHTML();
	return false;
}

function writemailBookTabClick(tab) {
	var _tab = ['addresswrite', 'stationery'];
	_tab.each(function(item) {
		if(item == tab) {
			Element.show($(item + 'book_ul'));
			$(item + 'book_li').style.cursor = 'text';
			switch(item) {
				case 'addresswrite':
					Element.addClassName($(item + 'book_li'), 'now1');
					break;
				case 'stationery':
					Element.addClassName($(item + 'book_li'), 'now2');
					break;
				default:
					break;
			}
		} else {
			$(item + 'book_li').className = '';
			$(item + 'book_li').style.cursor = 'pointer';
			Element.hide($(item + 'book_ul'));
		}
	});
}

// 信纸的预览图
function stationeryBookHTML(sta) {
	var str = [];
	sta.each(function(item, index) {
		if(index == 0) return;
		var _url = [MailConst.STATIONERY, '/', item, '_small.jpg'].join('');
		str.push(['<div class="s_letter letter-normal" bigletter="', item, '"><img src="', _url, '" style="padding: 1px; border: 1px solid #CFCFCF;" /></div>'].join(''));
	});
	var no_letter = '<div class="s_letter letter-normal" bigletter="no"><img src="'+ MailConst.ALL +'/unuse.gif" style="padding: 1px; border: 1px solid #CFCFCF;" /></div>';
	var letter_width = getRightPanelWidth() - staticValue.writeAddrWidth - 86 - 30 - 20 - getMainSpaceWidth();
	var _html = [];
	_html.push('<table cellpadding=0 cellspacing=0 style="width:100%;background-color:#EEEEEE;margin-bottom:3px;"><tbody><tr><td style="width:86px;">'+ no_letter +'</td>');
	_html.push('<td style="width:15px;vertical-align:middle;text-align:right;"><div id="letter_scroll_left" class="s_letter_left" style="display:block;"><img src="'+ MailConst.ALL +'/jiantou1.gif" style="cursor:pointer;" /></div></td>');
	_html.push('<td style="width:auto;"><div id="letter_area" style="width:'+ letter_width +'px;white-space:nowrap;overflow:hidden;"><div id="letter_scroll_area" style="overflow:hidden;width:950px;">'+ str.join('') +'</div></div></td>');
	_html.push('<td style="width:15px;vertical-align: middle;"><div id="letter_scroll_right" class="s_letter_right" style="display:block;"><img src="'+ MailConst.ALL +'/jiantou2.gif" style="cursor:pointer;" /></div></td></tr></tbody></table>');
	return _html.join('');
}

// 传情贺卡的预览图
function conveyBookHTML() {
	var _convey = ['convey1', 'convey2', 'convey3', 'convey4'];
	var str = [];
	_convey.each(function(item, index) {
		var _url = [MailConst.STATIONERY + '/../convey/', item, '.jpg'].join('');
		str.push(['<div class="s_convey letter-normal" bigconvey="', (index+1), '"><img src="', _url, '" style="width:66px;height:48px;padding:1px;border:1px solid #CFCFCF;" /></div>'].join(''));
	});
	var no_convey = '<div class="s_unuse_convey letter-normal" bigletter="no"><img src="'+ MailConst.ALL +'/unuse.gif" style="padding: 1px; border: 1px solid #CFCFCF;" /></div>';
	var _html = [];
	_html.push('<table cellpadding=0 cellspacing=0 style="width:100%;background-color:#EEEEEE;margin-bottom:3px;"><tbody><tr>');
	_html.push('<td style="width:180px;"><div style="margin:10px auto auto 10px;white-space:nowrap;"><span><select id="freq_selector"><option>每周一封</option><option>每月一封</option></select></span><span style="margin-left:10px;"><select id="week_selector"><option>请选择</option><option>星期天</option><option>星期一</option><option>星期二</option><option>星期三</option><option>星期四</option><option>星期五</option><option>星期六</option></select></span></div><div style="margin:10px auto auto 10px;white-space:nowrap;"><span><input id="cc_myself" type="checkbox" style="margin-left:0px;padding-left:0px;" /></span><span>抄送给自己</span></div></td>');
	// _html.push('<td style="width:86px;">'+ no_convey +'</td>');
	_html.push('<td style="width:auto;"><div id="convey_show_area" style="white-space:nowrap;overflow:hidden;"><div id="convey_scroll_area" style="overflow:hidden;">'+ str.join('') +'</div></div></td>');
	_html.push('</tr></tbody></table>');
	return _html.join('');
}
// 已经定制了传情计划的预览图
function conveyDisabledBookHTML(data) {
	data = data.evalJSON();
	var _convey = ['convey_disabled1', 'convey_disabled2', 'convey_disabled3', 'convey_disabled4'],
	_type = ['日常问候', '商务问候', '魔法情书', '健康养生'],
	_fq = data.freq ? '每月一次' : '每周一次',
	_t = _type[data.typeid];
	var str = [];
	_convey.each(function(item, index) {
		var _url = [MailConst.STATIONERY + '/../convey/', item, '.jpg'].join('');
		str.push(['<div class="letter-normal" bigconvey="', (index+1), '"><img src="', _url, '" style="width:66px;height:48px;padding:1px;border:1px solid #CFCFCF;" /></div>'].join(''));
	});
	var _html = [];
	_html.push('<table cellpadding=0 cellspacing=0 style="width:100%;background-color:#EEEEEE;margin-bottom:3px;"><tbody><tr>');
	_html.push('<td style="width:180px;"><div style="margin:10px auto auto 10px;white-space:nowrap;">您已定制了'+ _fq +'的'+ _t +'。<br />需要 <input type="button" value="取消定制" class="s_cancel_convey" style="height:28px;line-height:24px;cursor:pointer;"> 才能制定新的计划</div></td>');
	_html.push('<td style="width:auto;"><div id="convey_show_area" style="white-space:nowrap;overflow:hidden;"><div id="convey_scroll_area" style="overflow:hidden;">'+ str.join('') +'</div></div></td>');
	_html.push('</tr></tbody></table>');
	return _html.join('');
}
	 

// 是否显示组列表信息
function isShowAddrGroup(thisobj, obj) {
	if($(obj).visible()) {
		thisobj.src = MailConst.ALL +'/icon_bottom1.gif';
		thisobj.title = "组信息展开";
		$(obj).hide();
	} else {
		thisobj.src = MailConst.ALL +'/icon_top1.gif';
		thisobj.title = "组信息收回";
		$(obj).show();
	}
}

// 根据用户昵称获得用户邮件地址
function getEmailByNick(nick) {
	var email = "";
	contactLists.each(function(e) {
		if(e.name == nick) {
			email = e.email;
		}
	});
	return email;
}

// 点击组信息，将组联系人列表添加到写信栏
function inputGroupMail(group_name) {
	if(group_name) {
		var _obj = $(src_focus_id);
		if(_obj.value.startsWith('最多18个收件人')) {
			_obj.value = '';
		}
		_obj.focus();
		var c = _obj.value.split(",");
		var cc = false;
		c.each(function(e) {
			if(e == group_name) {
				cc = true;
			}
		});
		if(!cc) {
			var v = _obj.value.strip();
			if(v != "" && !v.endsWith(",")) {
				_obj.value += "," + group_name + ",";
                if(write_mail_single_flag == 1){
                try{
            		var toTmpList = writemail.getSendEmail2ArrayList(_obj.value);
                    var ad_list = toTmpList.uniq();
                    $('compose.wto').value = ad_list.join(",");
                }catch(e){}
            }
				return;
			}
			_obj.value += group_name + ",";
		}
        if(write_mail_single_flag == 1){
            try{
        		var toTmpList = writemail.getSendEmail2ArrayList(_obj.value);
                var ad_list = toTmpList.uniq();
                $('compose.wto').value = ad_list.join(",");
            }catch(e){
                alert(e);
            }
        }
	}
}

function showAddressCard() {
	var tb = {
		top : (Position.page($("address_card"))[1] + 20)
				+ Position.realOffset($("address_card"))[1] + "px",
		left : ((Position.page($("address_card"))[0] + 20) - 300) + "px"
	};
	addressCard.draw('', '', tb);
}

function addStationery2Writemail(obj, sta) {
	if (!writemail.defaulteditor || writemail.defaulteditor.toLowerCase() != "html") {
		_dialog.alert({info: '纯文本模式下不能使用信纸功能，请切换到HTML模式下！'});
		return false;
	}
	var getSta = Editor.c().document.getElementById("sohu_mail_stationery_name");
	var fcolor = sta.include('aoyun') ? '#FFF' : '#666666';
	var xline = sta.include('aoyun') ? 'aoyun_line.gif' : 'xinzhi_line.gif';
	var staContent = ['<table id="sohu_mail_stationery_name" background="',
			          MailConst.STATIONERY,
			      	  '/',
					  sta,
					  '.jpg" style="background-repeat:no-repeat;" cellpadding="0" cellspacing="0" width="99%">',
					  '<tbody>',
			          '<tr><td height="60px">&nbsp;</td></tr>',
					  '<tr>',
					  '<td width="15%">&nbsp;</td>',
					  '<td id="sohu_mail_stationery_line" style="line-height: 25px; color: '+ fcolor +'; font-size: 12px; background-repeat: repeat;" background="',
					  MailConst.STATIONERY,
					  '/'+ xline +'" valign="top" width="80%">',
					  '<div><STATIONERY>亲爱的朋友：<br/>　　您好！<br/></STATIONERY>',
					  '<div id="sohu_mail_stationery_content">',
					  '<div>&nbsp; <span> </span></div>',
					  '<div>&nbsp; <span> </span></div>',
					  '<div>&nbsp; <span> </span></div>',
			          '<div>&nbsp; <span> </span></div>',
					  '<div>&nbsp; <span> </span></div>',
					  '</div>',
					  '<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;致<br/>礼！',
					  '<br/><br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span>',
					  (mailCfgClass.getProfileContent().fullname ? mailCfgClass.getProfileContent().fullname : SUID),
					  '</span><br/><br/>',
					  '<STATIONERY></STATIONERY>',
			          '</div>',
					  '</td>',
					  '<td width="5%">&nbsp;</td>',
					  '</tr>',
					  '<tr><td height="60px">&nbsp;</td></tr>',
					  '</tbody>',
					  '</table>',
					  '<div style="padding:6px;color:#888888;right:20px;float:right;">Copyright © 搜狐公司 版权所有. All rights reserved. </div>'].join('');

	var mail_content = writemail.getContentInput();
	if (!getSta) {
		writemail.setContentInput(staContent);
		if (mail_content != "") {
			var si = "";
			Editor.c().document
					.getElementById("sohu_mail_stationery_content").innerHTML = mail_content.replace(/\<p\>/g,'<div>').replace(/\<\/p\>/g,'<\/p>').replace(/\<p\/\>/g,'<div\/>')
					+ "<div>&nbsp;</div><div>&nbsp;</div><div>&nbsp;</div>";
			if (Editor.c().document.getElementById("addMailSign")
					&& Editor.c().document
							.getElementById("addMailSign").innerHTML != "") {
				si = Editor.c().document
						.getElementById("addMailSign").innerHTML;
				Editor.c().document.getElementById("addMailSign").innerHTML = "";
				Editor.c().document.getElementById("addMailSign").id = "";
				writemail.setContentInput(writemail.getContentInput()
						+ '<div id="addMailSign">' + si + '</div>');
			}
		}
	} else {
		Element.setStyle(getSta, {backgroundImage: 'url(\'' + MailConst.STATIONERY + '/' + sta + '.jpg\')'});
		Element.setStyle(Editor.c().document.getElementById('sohu_mail_stationery_line'), {backgroundImage: 'url(\'' + MailConst.STATIONERY + '/' + xline + '\')', color: fcolor});
	}
	// changeStationeryPreviewClass(obj);
}

function noStationery2Writemail(obj) {
	/*
	if (writemail.defaulteditor == "text") {
		alert("纯文本模式下不能使用信纸功能，请切换到HTML模式下！");
		return;
	}
	*/
	try {
		if (Editor.c().document
				.getElementById("sohu_mail_stationery_content")) {
			var _sign = '';
			if (Editor.c().document.getElementById("addMailSign")) {
				_sign = Editor.c().document
						.getElementById("addMailSign").innerHTML;
				_sign = '<div id="addMailSign">' + _sign + '</div>';
			}
			writemail.setContentInput(Editor.c().document
					.getElementById("sohu_mail_stationery_content").innerHTML
					+ _sign);
		}
	} catch (e) {}
	// changeStationeryPreviewClass(obj);
}

function changeStationeryPreviewClass(obj) {
	// obj = obj.parentNode;
	var sobj = $("stationerybook_ul").getElementsByTagName("li");
	for (var i = 0; i < sobj.length; i++) {
		with(sobj[i].style) {
			border          = '0px';
			backgroundColor = 'transparent';
			padding         = '6px';
		};
		sobj[i].setAttribute('sel', 'false');
	}
	with(obj.style) {
		border          = '1px solid #f7941c';
		backgroundColor = '#fff6ca';
		padding         = '5px';
	};
	obj.setAttribute('focus', 'true');
}

function _editorChange() {
	if (writemail.isHtmlEditor()) {
		// DOM.compose_editer.innerHTML = '切换为纯文本';
		DOM.compose_mess1.show();
		DOM.compose_mess2.hide();
	} else {
		// DOM.compose_editer.innerHTML = '切换为HTML';
		DOM.compose_mess2.show();
		DOM.compose_mess1.hide();
	}
}


function _composeMailCallBack_Pageview(context) {
	DOM.compose_wto.value = context.to;
	DOM.compose_wcc.value = context.cc;
	DOM.compose_wbcc.value = context.bcc;
	DOM.compose_subject.value = context.subject;
	_editorChange();
	if (context.htmleditor && context.autoinclude) {
		Editor.setContent(context.context);
		context.context = Editor.getContent();
	}
	if (!context.htmleditor) {
		$("editor.mess2").value = context.context;
	}

	if (context.authenable) {
		$("compose.authcode").show();
	} else {
		$("compose.authcode").hide();
	}
	clicksave(context.autosave == "true" ? true : false);
}

function clicksave(isChecked) {
	writemail._clickSave(isChecked ? true : false);
	writemail.is_save = isChecked;
}

function writeMailAtNewWindow(param) {
	window.open(MailConst.CONTEXT
			+ '/action/composeMailAction?new_window=true&' + param, USE_SYS.title + '邮箱',
			'height=380px,width=600px');
}

/*************************** 撰写普通邮件和明信片邮件 *******************************/
function writeCommonMail() {
	changePanel('composeMail');
}

function writeCardMail() {
    jsoplog.ucCapture( 'cardmailclick' );
	changePanel('composeCardMail');
}

function writeCustomMail() {
    jsoplog.ucCapture( 'custommailclick' );
	changePanel('userMail');
}

function addressBookHTML() {
	var str1 = [];
	var str2 = [];
	str1.push('<ul>');
	var _rec_flag = recentLists.length > 0 ? true : false;
	
	if (contactLists.length > 0 || recentLists.length > 0) {
		contactCates.each(function(e) {
			if(e.id == 0) {
				str2.push('<div style="margin:4px 0px;font-family: Arial;clear:both;height:20px;"><div style="float:left;width:auto;height:100%;"><img title="组信息收回" gid="group_'+ e.id +'" class="s_show_group" style="cursor:pointer;margin:4px auto 4px 8px;" src="'+ MailConst.ALL +'/icon_top1.gif" /></div><div style="cursor:pointer;float:left;" title="向组联系人发信" class="s_group_input" gname="'+ e.name +'">'+ e.name.truncate(20, "...") +' <span>('+ contactLists.length +')</span></div></div>');
			 	str2.push('<div id="group_'+ e.id +'" style="display:block;">');
				contactLists.each(function(el) {
					if(!el || !el.email || !el.nickname) return false;
					str2.push('<li><a hidefocus="true" href="./main" title="' + el.email + '" cname="'+ el.nickname +'" cemail="'+ el.email +'" class="ps s_address_input">'+ el.nickname.truncate(20, '...') +'</a></li>');
				});
				str2.push('</div>');
			} else {
				var _str1 = [];
				if(e.id == -1) {
					_str1.push('<div id="group_'+ e.id +'" style="'+ (_rec_flag ? 'display:block;' : 'display:none;') +'">');
					var recentSlice1 = recentLists.slice(0, 6);
					var recentSlice2 = recentLists.slice(6);
					
					var confunc_item = function(item) {
						return '<li style="cursor:pointer;"><a hidefocus="true" href="./main" class="ps s_address_input" cname="'+ item.nickname +'" cemail="'+ item.email +'" title="' + item.email + '">' + item.nickname.truncate(20, "...") + '</a></li>';
					};
					_str1.push('<div>');
					recentSlice1.each(function(item) {
						_str1.push(confunc_item(item));
					});
					_str1.push('</div>');
					
					if (recentSlice2.length > 0) {
						_str1.push('<div style="display:none;">');
						recentSlice2.each(function(item){
							_str1.push(confunc_item(item));
						});
						_str1.push('</div>');
						_str1.push('<div style="float:right;color:red;margin-right:10px;"><a hidefocus="true" href="./main" class="s_address_more"> 查看更多↓ </a></div>');
					}
				} else {
					_str1.push('<div id="group_'+ e.id +'" style="display:none;">');
					contactLists.each(function(item){
						if (e.contactid.include(item.id)) {
							_str1.push('<li style="cursor:pointer;"><a hidefocus="true" href="./main" class="ps s_address_input" cname="'+ item.nickname +'" cemail="'+ item.email +'" title="' + item.email + '">' + item.nickname.truncate(20, "...") + '</a></li>');
						}
					});
				}
				_str1.push('</div>');
				var _l = e.contactid.split(',');
				_l = (e.id == -1) ? recentLists.length : (_l[0] == '' ? 0 : _l.length);
				e.id == -1 ? str1.push('<div style="margin:4px 0px;font-family: Arial;clear:both;height:20px;"><div style="float:left;width:auto;height:100%;"><img title="'+ (_rec_flag ? '组信息收回' : '组信息展开') +'" gid="group_'+ e.id +'" class="s_show_group" style="cursor:pointer;margin:4px auto 4px 8px;" src="'+ MailConst.ALL +'/'+ (_rec_flag ? 'icon_top1.gif' : 'icon_bottom1.gif') +'" /></div><div style="cursor:pointer;float:left;" title="向组联系人发信" class="s_group_input" gname="'+ e.name +'">'+ e.name.truncate(20, "...") +' <span>('+ _l +')</span></div></div>') :
				str1.push('<div style="margin:4px 0px;font-family: Arial;clear:both;height:20px;"><div style="float:left;width:auto;height:100%;"><img title="组信息展开" gid="group_'+ e.id +'" class="s_show_group" style="cursor:pointer;margin:4px auto 4px 8px;" src="'+ MailConst.ALL +'/icon_bottom1.gif" /></div><div style="cursor:pointer;float:left;" title="向组联系人发信" class="s_group_input" gname="'+ e.name +'">'+ e.name.truncate(20, "...") +' <span>('+ _l +')</span></div></div>');
				str1.push(_str1.join(''));
			}
		});
		str1 = str1.concat(str2);
	} else {
		str1.push('<li><a hidefocus="true" href="./main" class="ps s_no_addr_add">添加联系人</a></li>');
	}
	str1.push('</ul>');
	return str1.join('');
}

// 写信功能的地址本列表中最近联系人的全部展开和收回
function isShowAllRecent(el) {
	var _el = el.parentNode.previousSibling;
	if(Element.visible(_el)) {
		Element.hide(_el);
		el.innerHTML = ' 查看更多↓ ';
	} else {
		Element.show(_el);
		el.innerHTML = ' 折叠↑ ';
	}
}

// new code
function templBookHTML() {
	var str = [], scroll_width = 0;
	var _cardlist = CARDLIST.evalJSON();
	var _index = arguments[0] ? arguments[0] : 0;
	_cardlist[_index].each(function(item, index) {
		var _url = MailConst.CSS + '/../../postcard/' + item.tmpthumb;
		str.push(['<div class="s_postcard letter-normal" pindex="'+ _index +','+ index +'"><img src="', _url, '" style="width:66px;height:48px;padding:1px;border:1px solid #CFCFCF;" /></div>'].join(''));
		scroll_width = (86 * (index + 1)) + 4;
	});
	var no_letter = '<div class="s_unuse_postcard letter-normal" bigletter="no"><img src="'+ MailConst.ALL +'/unuse.gif" style="padding: 1px; border: 1px solid #CFCFCF;" /></div>';
	var _str = [];
	POSTCARDSEQ.each(function(item, index) {
		if (index == _index) {
			_str.push('<option selected>' + item.desc + '</option>');
		} else {
			_str.push('<option>' + item.desc + '</option>');
		}
	});
	var select_card = '<div style="width:100px;"><div style="margin:10px auto auto 10px;"><select onchange="changeTmpleteClass(this.selectedIndex);">'+ _str +'</select></div>'
					 +'<div id="upload_photo" style="width:80px;height:20px;position:relative;margin:10px auto auto 10px;"><span class="am upload-imgicon"></span><span>上传照片</span></div></div>';
	var card_width = getRightPanelWidth() - staticValue.writeAddrWidth - 30 - 100 - 20 - getMainSpaceWidth();
	var _html = [];
	_html.push('<table cellpadding=0 cellspacing=0 style="width:100%;background-color:#EEEEEE;margin-bottom:3px;"><tbody><tr>');
	_html.push('<td style="width:100px;">'+ select_card +'</td>');
	_html.push('<td style="width:15px;vertical-align:middle;text-align:right;"><div id="card_scroll_left" style="display:block;"><img src="'+ MailConst.ALL +'/jiantou1.gif" style="cursor:pointer;" /></div></td>');
	_html.push('<td style="width:auto;"><div id="card_parent_area" style="width:'+ card_width +'px;white-space:nowrap;overflow:hidden;"><div id="card_scroll_area" style="overflow:hidden;width:'+ scroll_width +'px;">'+ str.join('') +'</div></div></td>');
	_html.push('<td style="width:15px;vertical-align: middle;"><div id="card_scroll_right" style="display:block;"><img src="'+ MailConst.ALL +'/jiantou2.gif" style="cursor:pointer;" /></div></td></tr></tbody></table>');
	return _html.join('');
}

// 改变明信片的类型
function changeTmpleteClass(index) {
	var _cardlist = CARDLIST.evalJSON();
	var str = [], scroll_width = 0, _csa = $('card_scroll_area');
	_cardlist[index].each(function(item, _index) {
		var _url = MailConst.CSS + '/../../postcard/' + item.tmpthumb;
		str.push(['<div class="s_postcard letter-normal" pindex="'+ index +','+ _index +'"><img src="', _url, '" class="letter-image" /></div>'].join(''));
		scroll_width = (86 * (_index + 1)) + 4;
	});
	_csa.setStyle({width: scroll_width + 'px'});
	_csa.innerHTML = str.join('');
	try {
		writemail.focusLetterEL = _csa.firstChild;
		Element.addClassName(_csa.firstChild, 'letter-focus');
	} catch(e) {}
	try {
		changePostcardTemplate(_cardlist[index][0]);
	} catch(e) {}
}

function clickCardSubmit() {
	writecardmail.clickSendCard();
	jsoplog.ucCapture( 'clickpostcard' );
}

function clickCardSubmit2() {
	writecardmail.clickSendCard2();
}


// 明信片上滑块的事件

function postcardSliderShow(el) {
	el.style.visibility = 'visible';
}

function postcardSliderHide(el) {
	el.style.visibility = 'hidden';
}

function sliderTopLight(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '0px 0px -93px -36px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') -36px 0px no-repeat';
}

function sliderTopNormal(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '0px -36px -93px 0px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') 0px 0px no-repeat';
}

function sliderBottomLight(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '-99px 0px 0px -36px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') -36px -99px no-repeat';
}

function sliderBottomNormal(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '-99px -36px 0px 0px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\')  0px -99px no-repeat';
}

function sliderHandleLight(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '-37px 0px -73px -36px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') -36px -37px no-repeat';
}

function sliderHandleNormal(el) {
	if (is_ie6) {
		el.style.filter = '';
		el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
		el.style.margin = '-27px 0px -83px -36px';
		return;
	}
	el.style.background = '';
	el.style.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') -36px -27px no-repeat';
}

// 改变模板资源
var is_ie6 = (function() {
	try {
		return Prototype.Browser.IE && getBrowserVersion() <= 6.0;
	} catch(e) {
		return false;
	}
})(); 
function changePostcardTemplate(pro, el) {
	var _value = '';
	if($('postcard_textarea')) _value = $('postcard_textarea').value;
	writecardmail.cardMailChange = true;
	var postcard_tmp  = function(el) {
		if(is_ie6) {
			el.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+ MailConst.CSS +'/../../postcard/'+ pro.tmpurl +'")';
		} else {
			with(el.style) {
				backgroundColor  = 'transparent';
				backgroundImage  = 'url("'+ MailConst.CSS +'/../../postcard/'+ pro.tmpurl +'")';
				backgroundRepeat = 'no-repeat';
			};
		}
		with(el.style) {
			width      = pro.tmpwidth + 'px';
			height     = pro.tmpheight + 'px';
		};
		$('postcard_option_area').style.height = pro.tmpheight + 10 + 'px';
	};
	var postcard_area = function(el) {
		with(el.style) {
			width     = pro.areawidth + 'px';
			height    = pro.areaheight + 'px';
			left        = pro.arealeft + 'px';
			top         = pro.areatop + 'px';
			// fix IE 6 bug
			if (Prototype.Browser.IE && el.id == 'postcard_area') {
				backgroundColor = '#fff';
				filter          = 'Alpha(opacity=1)';
			}
		}
	};
	var postcard_area_range = function(el) {
		with(el.style) {
			width     = pro.areawidth + 'px';
			height    = pro.areaheight + 'px';
			top       = (pro.areatop - 2) + 'px';
			left      = (pro.arealeft - 2) + 'px';
		};
	};
	var postcard_textarea = function(el) {
		with(el.style) {
			left          = pro.textleft + 'px';
			top           = pro.texttop + 'px';
			width         = pro.textwidth + 'px';
			height        = pro.textheight + 'px';
			color         = pro.textcolor;
		};
		if(_value != '') $('postcard_textarea').value = _value;
		el.onfocus = function() {
			if(this.value == '点击这里填写内容．．．') this.value = '';
		};
		el.onblur = function() {
			if(this.value.strip() == '') this.value = '点击这里填写内容．．．';
		}
	};
	var postcard_textarea_range = function(el) {
		with (el.style) {
			left          = (pro.textleft - 2) + 'px';
			top           = (pro.texttop - 2) + 'px';
			width         = pro.textwidth + 'px';
			height        = pro.textheight + 'px';
		};
	};
	var postcard_slider = function(el) {
		with (el.style) {
			left  = (pro.sliderleft - 4) + 'px';
			top   = (pro.slidertop - 4) + 'px';
		};
	};
	var data = {};
	var user_set_url = mailUploadPhoto.isUser == true ? mailUploadPhoto.uploadUrl + '?uname=' + writecardmail.userImg.imgurl : MailConst.CSS +'/../../postcard/'+ writecardmail.userImg.imgurl;
	data['imgurl'] = writecardmail.userImg.imgurl == undefined ? MailConst.CSS +'/../../postcard/'+ pro.imgurl : user_set_url;
	postcard_area($('postcard_area'));
	postcard_area($('postcard_area').nextSibling);
	postcard_tmp($('postcard_tmp'));
	postcard_textarea($('postcard_textarea'));
	postcard_area_range($('postcard_area_range'));
	postcard_textarea_range($('postcard_textarea_range'));
	postcard_slider($('postcard_slider'));
	postCard.imgProperty = pro;
	if (writecardmail.userImg.imgurl != undefined) {
		postCard.imgProperty.imgurl = writecardmail.userImg.imgurl;
		postCard.imgProperty.imgwidth = writecardmail.userImg.imgwidth;
		postCard.imgProperty.imgheight = writecardmail.userImg.imgheight;
	}
	postCard.init(postCard.imgProperty);
	postCard.resetPostcard();
	postCard.scrollImg(null, pro.imgrate);
	$('user_image').src = data['imgurl'];
}

// 改变图片资源
function changePostcardPhoto(imgurl, ret, user, el) {
	user ? mailUploadPhoto.isUser = true : mailUploadPhoto.isUser = false;
	writecardmail.cardMailChange = true;
	try {
		postCard.imgProperty.imgurl = writecardmail.userImg.imgurl = ret.imgurl;
		postCard.imgProperty.imgwidth = writecardmail.userImg.imgwidth = ret.imgwidth;
		postCard.imgProperty.imgheight = writecardmail.userImg.imgheight = ret.imgheight;
	} catch(e) {}
	postCard.init(postCard.imgProperty);
	postCard.resetPostcard();
	postCardSlider._setHandlePos(0);
	$('user_image').src = imgurl;
}

function userPhotoPrev() {
	var i=0;
	var _prev = function() {
		if(i<9) {
			setTimeout(function() {
				$('upload_photo_info').parentNode.scrollLeft -= 10;
				_prev();
				i++;
			}, 10);
		} else { }
	};
	_prev();
}

function userPhotoNext() {
	var i=0;
	var _next = function() {
		if(i<9) {
			setTimeout(function() {
				$('upload_photo_info').parentNode.scrollLeft += 10;
				_next();
				i++;
			}, 10);
		} else {
		}
	};
	_next();
}

var postCard = null;
var postCardSlider = null;
var WriteCardMail = Class.create();
WriteCardMail.prototype = {
	initialize: function() {
		this.userImg = {};
		this._r;
		this.data = {};
	},
	init: function() {
		this.initSliderCSS();
		this._r = arguments[0];
		this._init_card = arguments[1];
		this.is_tourial = arguments[2];
		if(PCTMP.length > 0) {
			this.initCardMail(PCTMP);
		} else {
			get_postcard({}, this.initCardMail.bind(this), function() {
				_dialog.alert({info: '系统错误，请重试'});
				changePanel('mainPage');
			});
		}
	},
	initCardMail: function(ret) {
		if (PCTMP.length == 0) PCTMP = ret;
		reBuildPostcardData(ret);
		this.sendSucMailList = [];
		this.sendSuc = false;
		mailUploadPhoto.FILES_INFOS = [];
		mailUploadPhoto.FILES_UPLOADING = [];
		mailUploadPhoto.isUser = false;
		this.userImg = {};
		// 如果不是在写信界面进入的明信片页面
		try {
			if (!DOM.composeMail.visible()) {
				hiddenAllPanel();
				DOM.composeMail.show();
				appendAddressBook();
				writemail.initAutocomplete();
			}
		} catch(e) {}
		// 初始化随机code,(反垃圾邮件)
		try {
			mail_send_e.init(['compose.wto'],6,UID+genKeyCode());
		} catch(e) {}
		this.cardMailChange = false;
		try {
			deleteLoadPage();
		} catch(e) {}
		try {
			if(writemail.focusLetterEL) {
				Element.removeClassName(writemail.focusLetterEL, 'letter-focus');
				writemail.focusLetterEL = null;
			}
		} catch(e) {}
		try {
			if(!DOM.top_operate_area) DOM.top_operate_area = $('top_operate_area');
			if(!DOM.bottom_operate_area) DOM.bottom_operate_area = $('bottom_operate_area');
			DOM.top_operate_area.innerHTML = postcard_top_html;
			DOM.bottom_operate_area.innerHTML = postcard_bottom_html;
		} catch(e) {}
		try {
			writemail.writeFunc.each(function(item, index) {
				var _item = $(item);
				if(index == 1) {
					try {
						_item.show();
						_item.style.visibility = 'visible';
					} catch(e) {}
				} else {
					try {
						_item.hide();
						_item.style.visibility = 'hidden';
					} catch(e) {}
				}
			});
		} catch(e) {}
		var _sco = $('select_card_operate');
		var _icd = this._init_card ? this._init_card : [0, 0];
		try {
			if (!this.scrollAnimation) {
				_sco.innerHTML = templBookHTML(_icd[0]);
				this.scrollAnimation = new ScrollAnimation('card_scroll_area');
				this.scrollAnimation.mouseWheel();
				var self = this;
				Event.observe('card_scroll_right', 'click', function(event){
					self.scrollAnimation.scrollRight();
				});
				Event.observe('card_scroll_left', 'click', function(event){
					self.scrollAnimation.scrollLeft();
				});
			}
		} catch(e) {}
		_sco.hide();
		this.scrollAnimation.slideDown(_sco, 70);
		// writemail._clickSave(writemail.is_save ? true : false);
		var self = this;
		DOM.compose_wto.value = '';
		DOM.compose_wcc.value = '';
		DOM.compose_wbcc.value = '';
		var _fname = (function() {
			try {
				return mailCfgClass.getProfileContent().fullname + '';
			} catch(e) {
				return SUID;
			}
		})();
		DOM.compose_subject.value = ((typeof _fname != 'undefined' && _fname != 'undefined' && _fname && !_fname.blank()) ? _fname : SUID) + ' 为你制作的明信片';
		Element.hide($('mail.cc'));
		Element.hide($('mail.bcc'));
		try {
			this.data['to'] = DOM.compose_wto.value;
			this.data['cc'] = DOM.compose_wcc.value;
			this.data['bcc'] = DOM.compose_wbcc.value;
			this.data['subject'] = DOM.compose_subject.value;
		} catch(e) {}
		try {
			mailUploadPhoto.init();
			mailUploadPhoto.createForm();
		} catch(e) {}
		try {
			Element.show(DOM.compose_wto.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling);
			Element.show(DOM.compose_wto.nextSibling.nextSibling.nextSibling);
		} catch(e) {}
		$('postcard_textarea').value = '点击这里填写内容．．．';
		try {
			if (postCard == null) postCard = new PostCard('user_image', 'postcard_area', 'postcard_textarea', 'postcard_tmp');
		} catch(e) {}
		try {
			if (postCardSlider == null) postCardSlider = new PostCardSlider('postcard_slider_handle', 'vertical');
		} catch(e) {}
		
		var _ct = setTimeout(function() {
			clearTimeout(_ct);
			_ct = null;
			var _cl = CARDLIST.evalJSON();
			// fix ie6 bug
			try {
				changePostcardTemplate(_cl[_icd[0]][_icd[1]]);
			} catch(e) {}
			try {
				try {
					var _csa = $('card_scroll_area').childNodes;
					writemail.focusLetterEL = _csa[_icd[1]];
					Element.addClassName(_csa[_icd[1]], 'letter-focus');
				} catch(e) {}
			} catch(e) {}
			var _user_image = $('user_image');
			_user_image.onload = function() {
				// fix ie6
				if (Prototype.Browser.IE) {
					postCard.scrollImg(null, _cl[_icd[0]][_icd[1]].imgrate + 1);
					postCard.scrollImg(null, _cl[_icd[0]][_icd[1]].imgrate);
					this.onload = null;
				}
			};
			self.cardMailChange = false;
		}, 10);
		try {
			deleteLoadPage();
		} catch(e) {}
		addAjaxHistory("postcardMail", "changePanel('composeCardMail', null, true);", "制作明信片", this._r);
	},
	initSliderCSS: function() {
		var _top_s = $('postcard_slider_top').style;
		var _body_s = $('postcard_slider_body').style;
		var _bottom_s = $('postcard_slider_bottom').style;
		var _slider_s = $('postcard_slider_handle').getElementsByTagName('div')[0].style;
		if(is_ie6) {
			_top_s.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
			_top_s.margin = '0px -36px -93px 0px';
			_body_s.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
			_body_s.margin = '-27px -36px 0px 0px';
			_bottom_s.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
			_bottom_s.margin =  '-99px -36px 0px 0px';
			_slider_s.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\''+ MailConst.ALL +'/zoombar.png\')';
			_slider_s.margin = '-27px 0px -83px -36px';
		} else {
			_top_s.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') 0 0 no-repeat';
			_body_s.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') 0 -27px no-repeat';
			_bottom_s.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') 0 -99px no-repeat';
			_slider_s.background = 'url(\''+ MailConst.ALL +'/zoombar.png\') -36px -27px no-repeat';
		}

	},
	clickSendCard: function() {
		var params = postCard.getImgPosition();
		try {
			var toList = writemail.getSendEmail2ArrayList($('compose.wto').value, true);
			var ccList = writemail.getSendEmail2ArrayList($('compose.wcc').value);
			var bccList = writemail.getSendEmail2ArrayList($('compose.wbcc').value);
			var to = toList.join(', ');
			var cc = ccList.join(', ');
			var bcc = bccList.join(', ');
			this.sendSucMailList = this.sendSucMailList.concat(toList).concat(ccList).concat(bccList);
		} catch(e) {
			return false;
		}
		try {
			mail_send_e.genuuid();
		} catch(e) {}
		params.securityCode = mail_send_e.UUID;
        params.sendtime = mail_send_e._sendtime;
		params.to = to;
		params.cc = cc;
		params.bcc = bcc;
		params.subject = $('compose.subject').value;
		params.is_save = writemail.is_save;
        params.single = write_mail_single_flag;
		params.addressbook_use_flag = writemail.addressbook_use_flag;
		params.addressbook_use_list = writemail.addressbook_use_list;
		// 测试版本的明信片端口参数
		params.port = 1;
		send_postcard(params, this.clickSendCardCallBack.bind(this), this.clickSendMailFailureCallBack.bind(this));
	},
	clickSendCard2: function() {
		var params = postCard.getImgPosition();
		params.is_papercard = 1;
		send_postcard(params, this.clickSendCardCallBack2.bind(this), this.clickSendMailFailureCallBack.bind(this));
	},
	clickSendCardCallBack : function(ret) {
		try {
			if (this.is_tourial) {
				var __tou__ = setTimeout(function(){
					clearTimeout(__tou__);
					__tou__ = null;
					try {
						get_newbee_type('complete_mission', 'invite_friends', 1);
					} catch (e) {}
				}, 100);
			}
		} catch(e) {}
		/*
		var _s = false;
		panelObjList.each(function(item) {
			if(item.name == 'composeCardMail' && item.show == false) {
				_s = true;
			}
		});
		if(_s) return;
		*/
		if (ret.is_success) {
			var t = new Template(sendSucAddContactListTemplate);
			var data = {};
			var emailList = [];
			var optionList = [];
			var autoSaveSendEmail = '';
			var promptGift = '';
			var tmpMailList;
			tmpMailList = writemail.stripEqualValue(this.sendSucMailList);
			writemail.tmpMailList = tmpMailList;
			tmpMailList.each(function(item) {
				if(!IsEmail(item, false)) return;
				emailList.push('<dd>' + item + ' &nbsp;&nbsp;</dd>');
				if (writemail.isNotInContactList(item)) {
					optionList.push('<li><a hidefocus="true" id="save_succ_'+ item +'" class="s_succ_save" eid="'+ item +'" href="javascript:;"> 添加到地址本 </a></li>');
				} else {
					optionList.push('<li>&nbsp;&nbsp;</li>');
				}
			}.bind(this));
			var atsv = mailCfgClass.getProfileContent().autosavesendmail;
			if (atsv) {
				var save_list = ret.save_list;
				var savelen = save_list.length;
				if (save_list && save_list.length > 0) {
					writemail.save_addr_list = [];
					save_list.each(function(item) {
						writemail.save_addr_list.push(item.id);
					}.bind(this));
				}
				if(savelen > 0){
					autoSaveSendEmail = '<li"><input type="checkbox" class="s_succ_group"> 将本次被保存成功的联系人添加到通讯组中。</li>';
				    autoSaveSendEmail += '<li id="groupel" style="display:none"></li>';
				}
			} else {
				autoSaveSendEmail = '<br /><input type="checkbox" class="s_set_send_save" value="" /> 以后都将我发过信的联系人自动添加到地址簿';
			}
			if(USE_SYS.name == 'sohu') getScoreInfo();
			
			data['emailList'] = emailList.join('');
			data['optionList'] = optionList.join('');
			data['autoSaveSendEmail'] = autoSaveSendEmail;
			$("compose.sendinfo").innerHTML = t.evaluate(data);
			hiddenAllPanel();
			this.sendSuc = true;
			changePanel("sendSuc");
			if(atsv) {
				writemail.sendSuccSaveMailList(ret.save_list);
			}
		} else {
            var desc_str = null, link_str = null;
			var t = new Template(SmtpPromptTemplete);
			var data = new Array;
            data[ 'link_prompt' ] = 'http://mail.sohu.com/info/policy/';
            data[ 'str_prompt' ] = '未知错误，请参考我们的错误信息';
            var ret_str = ret.error.split( '|' );
            if( ret_str.length > 1 ) {
                data[ 'str_prompt' ] = ret_str[ 0 ];
                data[ 'str_errcode' ] = ret.code;
                data[ 'link_prompt' ] = ret_str[ 1 ];
                this.create_smtpPromptMask();
                Element.insert($('sohuMailMain'), {bottom: t.evaluate( data )});
                //getWindowDimensions<--global functions :158
                var screen = getWindowDimensions();
                var _x = parseInt( screen.win_width -  600 )/2;
                var _y = parseInt( screen.win_height - 300 )/3;
                try{
                $( 'del_group_prompt_panel_one' ).parentNode.setStyle({left:_x+"px",top:_y+"px"});
                }
                catch( e ){
                }
                try{
                     var s = $('smtp_prompt_panel').getElementsByClassName( "justfinder" );
                     s[0].setStyle({left:_x+"px",top:_y+"px"});
                }
                catch( e ){ }
            }
			writemail.AutoStore.start();
			return;
		}
	},
	// 彩信部门合作的接口回调
	clickSendCardCallBack2: function(ret) {
		if(ret.is_success) {
			jsoplog.ucCapture('postcardsent');
			var _url = 'pspt='+ UserSohuID +'&picurl='+ ret.imgPath + '&refer=2003';
			window.open('http://m.sohu.com/ka/face/goMxpFromMail.jsp?' + _url);
		} else {
			_dialog.alert({info: '由于网络原因，您的明信片没有发送成功，请重试！'});
		}
	},

	clickSendMailFailureCallBack : function() {
		// mail_signature=0;
		removeDiv4Sending();
		Tips.hide();
		if (this.thisCurrentMailisSending) {
			this.thisCurrentMailisSending = false;
			_dialog.alert({info: '由于网络原因，您的邮件没有发送成功，请重试！'});
			writemail.AutoStore.start();
		}
		return;
	},
	isChanged: function() {
		if(DOM.compose_wto.value != this.data['to'] ||
		DOM.compose_wcc.value != this.data['cc'] ||
		DOM.compose_wbcc.value != this.data['bcc'] ||
		DOM.compose_subject.value != this.data['subject'] ||
		this.cardMailChange == true) {
			return true;
		}
		return false;
	},
	_clickSave : function(isChecked) {
		$("saveCheckbox3").checked = isChecked;
		$("saveCheckbox4").checked = isChecked;
	}
};
var writecardmail = new WriteCardMail();
